Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between "abc" and {"abc"} in C?

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]);
like image 743
user128026 Avatar asked Dec 13 '22 02:12

user128026


1 Answers

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);
like image 174
John Millikin Avatar answered Dec 31 '22 06:12

John Millikin