views:

459

answers:

3

Hi,

I'm trying to create a 2D array of chars to storage lines of chars. For Example:

lines[0]="Hello";
lines[1]="Your Back";
lines[2]="Bye";

Since lines has to be dynamically cause i don't know how many lines i need at first. 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 can't go over 200 chars. I keep getting errors like "error C2059: syntax error : 'for'" and such. Any ideas of what i did wrong?

+1  A: 

You tagged the question with C++ -- why not use a std::vector<std::vector<char> > for this?

Looking at the compiler error, it looks like you're missing a semicolon before one of your for loops -- the code you posted seems to work perfectly fine here.

Billy ONeal
At first i thought thats what i did, but if i get rid of the code the rest of program runs fine.
BigBirdy
@BigBirdy: That just means adding the for causes the semicolon missing to cause a problem parsing the code. Check again -- the code you posted compiles fine.
Billy ONeal
+1  A: 

For a start, it's a waste of time doing that first calloc since you immediately initialise them with the first for loop.

Having said that, there's nothing at all wrong with the code you've shown.

Therefore, either your error lies elsewhere or that's not the code you've posted. I suggest you post the exact error message along with a cut-and-pasted copy of the offending line and ten lines either side of it for context. That will make our lives a lot easier in helping you out.


The errors:

syntax error : 'for' syntax error : missing ')' before ';'
syntax error : missing ';' before '<' missing type specifier - int assumed

as shown in one of your comments is usually caused by unbalanced parentheses. Check all your ( and ) characters to ensure they're equal in number, and in the right place. It's probably because you're missing a ) in the statement before the for but that's just an educated guess since the code you posted does not have that problem.

paxdiablo
+3  A: 

No the code is not in a function.

You can't just put arbitrary statements outside of functions in C and C++. What you can do though is use a function to initialize the variable:

char** init_lines() {
    char** ln = /* ... */;
    // your allocations etc. here
    return ln;
}

char** lines = init_lines();
Georg Fritzsche
Thanks, works now. How come it needs to be in a function?
BigBirdy
C and C++ simply work that way, you can only have declarations and definitions outside of functions. I recommend reading a good introductory book, look e.g. here for C++: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list ... and here for C: http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list
Georg Fritzsche