c – Im getting Invalid Initializer, what am I doing wrong?
c – Im getting Invalid Initializer, what am I doing wrong?
You cant 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
}
Thats 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
}
Arrays arent assignable.
You should use memcpy to copy contents from testStr
to revS
memcpy(revS,testStr,50);
c – Im getting Invalid Initializer, what am I doing wrong?
Only constant expressions can be used to initialize arrays, as in your initialization of testStr
.
Youre 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, youll need to use strcpy
.