Here's the simple example program
#include <stdio.h>
#include <string.h>
const char *hello_string = "Hello";
int main(void)
{
char *world_string = " World";
static char hello_world[strlen(hello_string)+strlen(world_string)];
strcpy(&hello_world[0], hello_string);
strcat(&hello_world[0], world_string);
printf("%s\n", hello_world);
return 0;
}
The compiler output:
test.c: In function ‘main’:
test.c:9:13: error: storage size of ‘hello_world’ isn’t constant
static char hello_world[strlen(hello_string)+strlen(world_string)];
^
I realize the completely useless and unnecessary use of "static" in this case causes the error and with its removal things will compile fine. This is just a simple example to illustrate my question.
What I don't understand is why the storage size is not a constant when the "hello_string" is declared as const char * and its size is not going to change during the course of execution. Is this just a case of the compiler not being smart enough to know that?
When the compiler complains about storage size not being constant implicitly means compile-time constant, i.e. a value that the compiler can determine at compile-time. The call of strlen
obviously would happen at runtime, so the compiler cannot know the size of your array.
Try this:
#include <stdio.h>
#include <string.h>
const char hello_string[] = "Hello";
int main(void)
{
char world_string[] = " World";
static char hello_world[sizeof hello_string + sizeof world_string];
strcpy(&hello_world[0], hello_string);
strcat(&hello_world[0], world_string);
printf("%s\n", hello_world);
return 0;
}
strlen
is a function. It's return value cannot be calculated at compile time.
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