Arun wrote:
Hi all,
The code below gives compilation error (in gcc).
"initializer element is not constant" @line 11
1 #include <stdio.h>
2 char* ptr="string";
3 //char ptr[ ]="string";
4
5 typedef struct
6 {
7 char *c;
8 int i;
9 }test_struct;
10
11 test_struct s={ptr,10};
12
13
14 int main()
15 {
16
17 return 0;
18 }
But when comment Line 2 & uncomment line 3 it works fine. It also
works fine when i move line 11 into main function.
Can anybody tell me cause of this error.
Thanks,
Arun
You can only initialize global variables with values that are known at
compile time. Since "char *ptr" is a variable, it fails. "char ptr[]"
causes the compiler to allocate space to hold the string, so ptr in
this case is not an lvalue (cannot be assigned to) and the compiler is
happy to initialize test_struct with it.
To highlight the difference try to imagine how "STRING" and ptr are
allocated in memory. When you declare "char *ptr", what is stored at
ptr? The ADDRESS of "string". What is stored at ptr when you declare
"char ptr[]"?
I'm not sure I did a good job of explaining this, but I hope it helped.