Morpheus Morpheus - 3 months ago 16
C Question

I am getting a SegFault error, but why?

I am getting a Segmentation Fault error when I run the code, but other than that it compiles and runs. If you know why the error is occurring, I'd appreciate the help. Also please explain why it is occurring, as I'm curious.

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int main()
{
float att,def,hp,agi,stl,wis,ran,acc;
char name[10],contents[100];
int warrior,lvl=1,kills=0;

printf("What is your name?\n");
gets(name);

printf("1: Ninja\n");
printf("2: Knight\n");
printf("3: Archer\n\n");
printf("Pick a warrior.\n");
scanf("%i",warrior);

...

char attack[10],defense[10],health[10],agility[10],stealth[10],wisdom[10],range[10],accuracy[10],level[10],kill[10];
snprintf(attack,10,"%f",att);
snprintf(defense,10,"%f",def);
snprintf(health,10,"%f",hp);
snprintf(agility,10,"%f",agi);
snprintf(stealth,10,"%f",stl);
snprintf(wisdom,10,"%f",wis);
snprintf(range,10,"%f",ran);
snprintf(accuracy,10,"%f",acc);
snprintf(level,10,"%f",lvl);
snprintf(kill,10,"%f",kills);

char my_path[25];
strcat(my_path,"Warriors/");
strcat(my_path,name);
strcat(my_path,".txt");


FILE *fp;
fp = fopen(my_path, "w+");

fputs(attack, fp);
fputs(" ", fp);
fputs(defense, fp);
fputs(" ", fp);
fputs(health, fp);
fputs(" ", fp);
fputs(agility, fp);
fputs(" ", fp);
fputs(stealth, fp);
fputs(" ", fp);
fputs(wisdom, fp);
fputs(" ", fp);
fputs(range, fp);
fputs(" ", fp);
fputs(accuracy, fp);
fputs(" ", fp);
fputs(level, fp);
fputs(" ", fp);
fputs(kill, fp);

fclose(fp);
}

Answer
scanf("%i",warrior);

scanf expects a pointer. http://linux.die.net/man/3/scanf

Fix it to

scanf("%i", &warrior);
Comments