2

I’m trying to deference a char pointer to a char array inside a function:

void getword(char *word)
{
    *word = "bar";
}


int main()
{
    char defword[4] = "foo";
    getword(defword);

    printf("%s\n", defword);

    return 0;
}

I would expect to get "bar" as output but I seem to get the completely unrelated string '1oo'.

mc110
  • 2,825
  • 5
  • 20
  • 21
qwesr
  • 59
  • 1
  • 7
  • 1
    Try using strcpy() instead of just an assignment. – Happington Jun 16 '14 at 18:39
  • 5
    Do you have any compiler warnings enabled? That assignment in `getword()` (`char *` assigned to `char`) should be setting off at least one. – Paul Roub Jun 16 '14 at 18:39
  • I was actually getting a "integer from pointer without a cast [enabled by default]" Warning I just didn’t know what to make of it, but the strcpy definitely works thanks for the help! – qwesr Jun 16 '14 at 18:45

1 Answers1

5

The type of a dereferenced char * is char — a primitive value type. In this case, *word is the same as word[0].

The type of "bar" is const char * — a pointer type.

You are assigning the value of a pointer to a character. I'm doubtful your compiler let that happen without squawking mightily.

In any event, look into strcpy. Leaving aside the horrible unsafety of it all, this will work better:

strcpy(word, "bar");
0xbe5077ed
  • 4,565
  • 6
  • 35
  • 77
  • 1
    What exactly makes strcpy unsafe? Are there any safer alternatives? But that gets the job done, thanks! – qwesr Jun 16 '14 at 18:46
  • 1
    @qwesr, the fact it blindly copies into the destination buffer until it encounters a nul in the source buffer, without regard for the capacity of the destination buffer. As with many things in software, it's not *inherently* unsafe, _ie_ not if you use it properly. But because of its dangerous properties, it is much safer to be in the habit of a string copy function that knows about and respects destination buffer size. In some cases, that might be [`strncpy`](http://www.cplusplus.com/reference/cstring/strncpy/), but see [here](http://stackoverflow.com/q/869883/1911388) for a caution. – 0xbe5077ed Jun 16 '14 at 18:52
  • That's the bad thing about C, you need to be careful with your memory allocation. – Survaf93 Jun 16 '14 at 21:17