This is what I expect my string array s to be after the program is run: {"#0", "#1", "2"}.
This is what I am getting: {"#2", "#2", "2"}.
How do I modify this code so that I can get {"#0", "#1", "#2"} in the main after the function is executed?
What am I doing wrong? Please help.
#include <stdio.h>
void func(char **s){
for(int i=0; i<3; i++){
char buf[10];
snprintf(buf, 10, "#%d",i);
s[i]=buf;
}
}
int main()
{
char *s[3];
func(s);
for(int i=0; i<3; i++){
printf("%s", s[i]);
}
return 0;
}
@Chris’s answer tells you what is wrong.
To fix it, you have options. The simplest is to make the argument array have strings (char arrays) that are big enough for your uses:
If you want to play with dynamic
char *strings, life gets only a little more complicated:Ultimately the trick is to manage the size of your strings, remembering that a string is itself just an array of
char. You must ensure that there is enough room in your character array to store all the characters you wish. (Good job on usingsnprintf()!Also remember that in C any argument of the form
array[]is the same as*array. So our functions could have been written:or
respectively. The first is an uglier (harder to read) syntax. The second is nicer, methinks, but YRMV.
Finally, if you are using C99 (or later) you can tell the compiler that those arguments are, actually, arrays:
or
MSVC does not support that syntax, though, and probably never will, alas.