开发者

C - Setting a static char array with a "string"

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..开发者_如何学Go.

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.


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

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


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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜