In C specifically (i suppose this also applies to C++), what is the difference between
char str[4] = "abc";
char *cstr = {"abc"};
Problems arise when i try and pass my "abc" into a function that accepts char**
void f(char** s)
{
fprintf(stderr, "%s", *s);
}
Doing the following yields a compiler error. If cast to char** (to make compiler happy) program seg faults.
f(&str);
However the following works fine
f(&cstr[0]);
The first line line defines an array of four bytes. These two are equivalent:
char str[4] = "abc";
char str[4] = {'a', 'b', 'c', 0};
The second line declares a pointer to a memory location, which contains the bytes 'a', 'b', 'c', and 0. These two are equivalent:
char *cstr = {"abc"};
char *cstr = "abc";
Your problem arises from mixing char[]
and char*
. If the function accepts a char**
, you must create a char*
to get the address of:
char str[4] = "abc";
char *cstr = str;
f(&cstr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With