char sXSongBuffer[20][30];
sXSongBuffer = {"Thriller", "Don't Stop Till You Get Enough", "Billy Jean"};
Why does this return the error expected expression before ‘{’ token? The reason I want to initialize my array like this is so that I can change its contents like this later:
sXSongBuffer = {"New Song", "More Music From Me"};
You can’t assign to arrays in C. C allows initializing arrays with values that are compile-time constants. If you want to change the values later, or set values that are not compile-time constants, you must assign to a particular index of the array manually.
So, your assignment to
sXSongBufferis disallowed in C. Moreover, sincesXSongBuffer[0]tosXSongBuffer[19]are arrays too, you can’t even say:sXSongBuffer[0] = "New Song";Depending upon what you want, this may work for you:
But the above only works if you know all your strings at compile time. If not, you will have to decide if you want “big-enough” arrays, or if you need dynamic memory for the strings and/or the number of strings. In both cases, you will want to use an equivalent of
strcpy()to copy your strings.Edit: To respond to the comment:
sXSongBufferinchar *sXSongBuffer[30];is an array of size 30, with each element being achar *, a pointer tochar. When I do:each of those 30 pointers is uninitialized. When I do:
I set the pointers to different read-only locations. There is nothing preventing me to then “re-point” the pointers somewhere else. It is as if I had:
In the above snippet, I assign
datato"Hello"first, and then change it to point to a longer string later. The code I had above in my answer did nothing more than reassignsXSongBuffer[i]to something else later, and sincesXSongBuffer[i]is a pointer, the assignment is OK. In particular,sXSongBuffer[0]is achar *, and can point to any valid location that has acharin it.As I said later in my answer, if the strings aren’t known at compile-time, this scheme doesn’t work, and one has to either use arrays with “big enough” sizes, or dynamically allocate memory that’s big enough.