sscanf strangeness
Hello I am trying to compile a small program in C and I am a bit perplexed as to why I am getting a gcc warning to recast this.
the program uses this sscanf(argv[1],"%i%c%i",&option1,&throwaway,&option2); I do this to try and capture only the integers in the string I really don't care about the char in between. Is sscanf looking for a diffrent kind of variable to put the char into because I declared throwaway as char? Gcc keeps thinking im putting it into a integer? |
Quote:
... From the manpage: Code:
c Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there Do you expect just one character between the two integers ? |
Code:
#include<stdio.h> This is how it was compiled Code:
|
Quote:
Code:
char throwaway = NULL; Code:
char throwaway; |
Yeah that's what it is. Hmmm I guess null is considered a integer. Sorry if this seams like a stupid question, im just getting back into c programing again.
|
Quote:
Code:
(void *)0 |
Use zero instead of null or type (int)NULL.
|
Quote:
|
I thought you were supposed to initialize any variable because they can contain random data from where ever the memory was allocated from. The only way to be able to test for a condition is if you know exactly what will be there.
|
Quote:
Generally speaking, you need to initialize only those variables, whose value is going to be used before it comes "from outside" or is calculated. |
I would be afraid that sscanf might see more than one char and overflow your throwaway memory. I would actually allocate a buffer and pass the address of the buffer:
#include<stdio.h> #include<stdlib.h> int main(int argc, const char* argv[]) { int optionone = 0; int optiontwo = 0; char throwaway[20]; sscanf(argv[1],"%i%c%i",&optionone,throwaway,&optiontwo); printf("The options are %i and %i",optionone,optiontwo); return 0; } Because of the way C handles arrays and pointers, the address of the buffer as an array of char is referenced by the variable name or equivalently the address of the first element of the array, so I removed the unary prefix & from the modified code. I believe C would also accept &throwaway[0] as that parameter. I believe the correct way to initialize a single char variable would be a null char in single quotes: char throwaway = '\0'; If I allocated a buffer and wanted to initialize it, I would try char throwaway[20] = ""; All this is hypothetical, though. I did not actually compile and test it. |
scanf(3)
Quote:
|
All times are GMT -5. The time now is 10:07 PM. |