1

Could anyone give me an sample how to create a 2D char array in C by passing the variable for the array length.

//Current program
int i;
int seq_cnt;    
exec sql    
        select count(0)     
        into seq_cnt     
        from    table;    
char tmp1[50][5+1];       
char tmp2[50][5+1];   

for(i=0;i < seq_cnt ; i++){   
     strcpy(tmp1[i],"something");    
     strcpy(tmp2[i],"something");    
}     

Now what I want is for the array size of tmp1 and tmp2, I want to use the seq_cnt to declare the actual size of tmp1 and tmp2 instead of hardcode it (50).

like:

char tmp1[seq_cnt][5+1];     
char tmp2[seq_cnt][5+1];     

I'm new to C.

2
  • 2
    char tmp1[seq_cnt][5+1]; char tmp2[seq_cnt][5+1]; should work if you are using C99+. Or you can resort to dynamically allocating memory using malloc. Note: "something" won't fit into an array of size 5 + 1 Commented Jan 18, 2019 at 9:59
  • @Spikatrix: Depends on the compiler. Some VC version do not support VLAs. Also C11 made VLAs optional. C++ does not know them at all. Commented Jan 18, 2019 at 10:01

1 Answer 1

1

I want to use the seq_cnt to declare the actual size of tmp1

Do

char (*tmp1)[5+1] = malloc(seq_cnt * sizeof *tmp1);

Update on the three different usages of an asterisk * in C.

  1. Types/Variable definitions

    Here

    char (*tmp1)[5+1]
    

    the asterisk is used to define a pointer, a pointer to a char[5+1] array.

    Please not that the parentheses are mandatory, as char *tmp[5+1] would defined an array of 6 pointer to char.

  2. Indirection (or de-referencing) operator

    Here

    sizeof *tmp1
    

    the asterisk is used to tell the compiler to not take the size of tmp1 which would be the size of a pointer, but the size of what tmp1 points to, namely a char[5+1].

    Alternatively one could write sizeof (char[5+1]). Please note that the parenthesis are not belonging to sizeof as it is not a function, but an operator.

  3. Multiplication operator

    Here

    seq_cnt * sizeof ...
    

    the asterisk is used to indicate an ordinary multiplication, namely to calculate the product of seq_cnt and the size of something.

So all in all the top statement allocates seg_cnt times the bytes a char[5+1] needs and assigns the address of the 1st byte of the chunk allocated to tmp1, makes it point to enough memory to hold seq_cnt array of char[5+1].

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. This is what I want exactly . Could you mind explaining it more ? I am not familiar with malloc . and there is so many * that making me confused.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.