Error when assigning char* to structure member

A

Arun

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
 
I

insik.park

Arun said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top