I am programming in ansi C in a Linux environment, I am using gcc compiler. I have the following code
#define USER_IN_LEN 15
#define EXTRA_SPACES 2
#define DELIMS " ,\n"
//define the sruct
typedef struct position
{
int x;
int y;
} Position;
char choice[USER_IN_LEN + EXTRA_SPACES];
//define pointers for strtok and strtol
char *tok;
char *end;
//create pointer o type Position
Position *position;
//get user input with fgets
fgets(choice, USER_IN_LEN, stdin);
//tokenize
tok = strtok(choice, DELIMS);
tok = strtok(NULL, DELIMS);
position->x = (int)strtol(tok, &end, 0); //error, segmentation fault
tok = strtok(NULL, DELIMS);
position->y = (int)strtol(tok, &end, 0);//error, segmentation fault
Basically the program gets user input for some values and store them in the position struct, I have did some research online and found out I can use this position->y = int
, but why isn't it working here with strtol
? I ran the debugger and it didn't help much
position
is a pointer to a struct. You never set position
to any value, so it could be pointing anywhere! - i.e. you're invoking undefined behaviour.
Quick fix:
Position instance;
position = &instance;