1

Below program works:

int main()
{
    char *g[10];
    char a[10] = "test";
    g[0] = &a[0];
    printf("string = %s\n",g[0]);
    exit(0);
}

output : test

But this does not work:

int main()
{
    char t[] = "test";
    struct abc
    {
        char *a[255];
    }*p;
    p->a[0] = &t[0];
    printf("value = %s\n", p->a[0]);
    exit(0);
}

output : segmentation fault

Can somebody tell what may be problem in second part of code? Sorry if i have post here wrongly.

haccks
  • 104,019
  • 25
  • 176
  • 264

1 Answers1

3

In your second code you are using pointer p without initializing it. This lead to undefined behavior.
Try this

struct abc q;
p = &q;
p->a[0] = t;
printf("value = %s\n", p->a[0]);
haccks
  • 104,019
  • 25
  • 176
  • 264
  • @Gabson; This is really a nice question. `char *a[]` means `a` is array of pointers to `char`. `char *a` defines `a` as pointer to `char` while `char a[]` defines `a` as an array of `char`s. Further reading [Answer1](http://stackoverflow.com/a/18361686/2455888) and [Answer2](http://stackoverflow.com/a/18364638/2455888). – haccks Nov 14 '13 at 16:04