3

a very simple question I am afraid but I have been stuck for days with this, Google gives me nothing, I even tried bing... ;o)

I am working in pure C under windows in VS2010.

I have a static char array as such...

static char word[5];

I can set each array position just fine i.e...

word[0] = 'f'; word[1] = 'o'; word[2] = 'o';

But what I cannot seem to do (at any point after declaration) is...

word = "foo";

Any help or pointers as to where I am going wrong would be very much appreciated.

Thanks all in advance.

1
  • Any help or pointers? Punny :] Commented Apr 30, 2011 at 19:18

2 Answers 2

4
strncpy(word, "foo", _countof(foo));

If _countof is not defined, use sizeof(foo) / sizeof(*foo) instead.

Sign up to request clarification or add additional context in comments.

4 Comments

Lovely jubbly, Thanks Mehrdad that worked a charm. I am a C# guy by trade and finding nothing but respect for C guys after having a delve into this world. I will mark your answer as accepted as soon as it lets me.
@Nick: Haha sure, glad it helped. :) Yup I like C# too, but I found the need to learn C so I learned that too. C isn't that bad; C++ is another beast though!
yes I think its good to know C too, its good for learning what is going off at a lower level, I know too many developers that call very expensive operations in C# because they don't understand what that method call is doing back down at memory level.
@Nick: Absolutely. Even after you learn C, you should then learn about the CPU cache and how it works, because then you learn, for example, that if you're adding two arrays, the order of the loops (i then j vs j then i) can slow down your loop by like a factor of 10. :) (It's called locality of reference.)
2

Arrays are not pointers. Pointers are not arrays.

In most contexts, arrays decay to a pointer to its first element. That pointer is not modifiable though.

In

word = "foo";

the array word decays to a non-modifiable pointer to its first element ... and you try to modify that pointer by assigning it the address of the string literal "foo"

1 Comment

Thanks for your input pmg, I believe I understand the problem a little better thanks to this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.