By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,603 Members | 1,477 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,603 IT Pros & Developers. It's quick & easy.

Error when assigning char* to structure member

P: n/a
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

Nov 16 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a

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.

Nov 16 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.