I'm Getting "Invalid Initializer", What Am I Doing Wrong?
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?

6 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
}
4

Arrays arent assignable.

You should use memcpy to copy contents from testStr to revS

memcpy(revS,testStr,50);

Only constant expressions can be used to initialize arrays, as in your initialization of testStr.

You're trying to initialize revS with another array variable, which is not a constant expression. If you want to copy the contents of the first string into the second, you'll need to use strcpy.

An initializer for a char[] needs to be either a literal string or something like {1,2,3,4}. It isn't allowed to be the name of another variable.

Unless you plan on manipulating the second array you can also use a pointer:

int main(void){
    char textStr[50] = "hello worlds!";
    char *revS = textStr;
    printf("%s\n", revS);

}

If you want to get really crazy you can point to a specific location in the array with the reference operator:

int main(void){
    char textStr[50] = "hello worlds!";
    char *revS = textStr+5; // or &textStr[5]
    printf("%s\n", revS);
}

You are doing

char revS[50] = testStr; 

which is wrong since you cannot assign char * to char.

Try revS = testStr; it should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest