Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm getting "Invalid Initializer", what am I doing wrong?

Tags:

arrays

c

int main(void) {
    char testStr[50] = "Hello, world!";
    char revS[50] = testStr;
}

I get error: "invalid initializer" on the line with revS. What am I doing wrong?

like image 432
deadghost Avatar asked Jun 15 '12 00:06

deadghost


2 Answers

You can't initialise revS in that manner, you need a very specific thing to the right of the =. From C11 6.7.9 Initialization /14, /16:

14/ An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces.

Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

: : :

16/ Otherwise, the initializer for an object that has aggregate or union type shall be a brace-enclosed list of initializers for the elements or named members.


To achieve the same result, you could replace your code with:

int main (void) {
    char testStr[50] = "Hello, world!";
    char revS[50]; strcpy (revS, testStr);
    // more code here
}

That's not technically initialisation but achieves the same functional result. If you really want initialisation, you can use something like:

#define HWSTR "Hello, world!"
int main (void) {
    char testStr[50] = HWSTR;
    char revS[50] = HWSTR;
    // more code here
}
like image 68
paxdiablo Avatar answered Nov 18 '22 23:11

paxdiablo


Arrays arent assignable.

You should use memcpy to copy contents from testStr to revS

memcpy(revS,testStr,50);
like image 9
Tom Avatar answered Nov 18 '22 21:11

Tom