2

I have a struct that contains an array of strings but I'm lost regarding how to use it sometimes
For instance :

struct A
{
  char** b;
};

size_t two = 2;
struct A a = malloc(sizeof(struct A));
b = (char**) malloc(sizeof(char*) * 2);
a->b[0] = "1";
snprintf(a->b[1], 4, "%d", two); //this line makes a mess

It works perfectly fine if I use snprintf for a variable that I define as char* type, but isn't a->b[1] a char* type itself ?
Why doesn't it work (if I use a printf on a->b[1], it displays the value but the program crashes when I do any malloc afterward) and what should I do to make it work ?

Rob
  • 14,746
  • 28
  • 47
  • 65
user3548298
  • 186
  • 1
  • 1
  • 13

1 Answers1

2

This line

snprintf(a->b[1], 4, "%d", two);

dereferences a->b[1], which has not been set. You cannot write into it. If you would like to write into a->b[1], do it like that:

a->b[1] = malloc(4);
snprintf(a->b[1], 4, "%3d", two);

Now a->b[1] has a writeable block of memory of 4 bytes. %3d limits the output to three digits, in case variable two is set to a larger number.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Seems to work perfectly fine But I'm kinda disapoint that I have to manually do a malloc and not just point to a new value returned by the function :( Thank you – user3548298 Apr 09 '16 at 22:00
  • @user3548298 Apart from [non-standard `%sa`](http://stackoverflow.com/a/2330126/335858), there's no good option here :-( – Sergey Kalinichenko Apr 09 '16 at 22:03
  • The second argument to `snprintf()` limits the output. The `3` in `%3d` sets a different limit: the minimum field width. – cremno Apr 09 '16 at 22:09
  • 1
    Use `asprintf` if you want a function that allocates the memory for you. Non-standard, but available on Windows, OSX, Linux, *BSD and many others. – Chris Dodd Apr 09 '16 at 22:54