So I have this small part of my code (basically the input for my whole program).
It has to take the form of a string with at most 20 characters, and two integers all separated by a space.
eg master 1 1
int main(void)
{
int i, x, y;
char input[28];
char* name = NULL;
fgets(input, 28, stdin);
sscanf(input, "%s %i %i", name, &x, &y);
printf("%s %i %i\n", name, x, y);
return 0;
}
Basically I'm trying to print it out to see if the program is storing the input correctly, as it has to be stored in a linked list later on.
Everything worked fine, but no matter what I type, It prints out (null) 0 4196064. It seg faults if I put and ampersand infront of name in the sscanf() function as well.
Any ideas on how to fix this would be much appreciated!
sscanf will not allocate storage for your string.
char name[28];
will work. &name causes seg.fault, because that differs in levels of indirection. What you then pass is a char * * , which is interpreted as char * inside sscanf. As your name variable is on the stack, &name points to the stack, so sscanf will overwrite your stack content. That can easily result in a seg.fault.