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 ?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 Apart from non-standard %sa, there's no good option here :-(
The second argument to snprintf() limits the output. The 3 in %3d sets a different limit: the minimum field width.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.