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?
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
}
Arrays arent assignable.
You should use memcpy to copy contents from testStr
to revS
memcpy(revS,testStr,50);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With