2d array, using calloc in C

后端 未结 4 1261
长情又很酷
长情又很酷 2021-01-28 17:54

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\";

相关标签:
4条回答
  • 2021-01-28 18:13

    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();
    
    0 讨论(0)
  • 2021-01-28 18:17

    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.

    0 讨论(0)
  • 2021-01-28 18:17

    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.

    0 讨论(0)
  • 2021-01-28 18:18

    Here i'm opinion is different. May be useful. char pointer or char double is implicitly define during compilation. Hence it is not need to define explicitly and by doing so it show syntax error. Try char pointer without initializing by calloc and if you don't want garbage value initialize with NULL. It act like using calloc, you find nothing different.

    0 讨论(0)
提交回复
热议问题