2d using calloc in C
I am trying to create a 2D character array for strings to store characters. For example:
lines[0]="Hello";
lines[1]="Your Back";
lines[2]="Bye";
Since the lines have to dynamically result in I don't know how many lines I need at the beginning. Here is the code I have:
int i;
char **lines= (char**) calloc(size, sizeof(char*));
for ( i = 0; i < size; i++ ){
lines[i] = (char*) calloc(200, sizeof(char));
}
for ( i = 0; i < size; i++ ){
free(lines[i]);
}
free(lines);
I know that each line cannot be more than 200 characters long. I keep getting errors like "error C2059: syntax error:" for "etc. Any ideas of what I did wrong?
source to share
There is no code in the function.
You can't just put arbitrary expressions outside of functions in C and C ++. However, you can use a function to initialize a variable:
char** init_lines() {
char** ln = /* ... */;
// your allocations etc. here
return ln;
}
char** lines = init_lines();
source to share
For starters, it's a waste of time doing this first calloc
since you initialize them immediately with the first loop for
.
Having said that, there is nothing wrong with the code you showed.
Therefore, either your error lies elsewhere, or not the code that you posted. I suggest you submit the exact error message, along with a cut-and-paste copy of the offending line, and ten lines on each side for context. It will make life easier for us to help you.
Errors:
syntax error : 'for' syntax error : missing ')' before ';'
syntax error : missing ';' before '<' missing type specifier - int assumed
as shown in one of your comments, usually caused by unbalanced parentheses. Check all your symbols (
and )
to make sure they are equal in number and in the right place. Probably because you didn't specify )
in the sentence before for
, but this is just an enlightened guess as the code you posted doesn't have this issue.
source to share
Here I have a different opinion. May be helpful. char pointer or char double is implicitly defined at compile time. Hence there is no need for an explicit definition, nor does it show a syntax error. Try a char pointer without initializing calloc and if you don't want the garbage value to be initialized with NULL. It acts like calloc, you don't find anything else.
source to share