Referenced memory could not be written - c

Whenever I run this struct, I can get down to the line where you would input the constitution modifier and the program crashes with a popup window which reads "The instruction at 0x00000000775AFDE9 referenced memory at 0x000000007758D250. The memory could not be written. Press OK to terminate." Here's the struct in question:
struct player_info create_player(void);
struct player_info{
char name[30];
int Level, Str, Dex, Con, Int, Wis, Cha;
};
struct player_info create_player(void){
struct player_info aPlayer;
{
char c;
int i;
printf("Enter Player Name: ");
scanf("%s",aPlayer.name);
i = strlen(aPlayer.name);
do{
scanf("%c", &c);
aPlayer.name[i++] = c;
}
while (c != '\n');
aPlayer.name[i - 1] = 0;
}
printf("Level: ");
scanf("%d",aPlayer.Level);
printf("Strength Modifier: ");
scanf("%d",aPlayer.Str);
printf("Dexterity Modifier: ");
scanf("%d", aPlayer.Dex);
printf("Constitution Modifier: ");
scanf("%d", aPlayer.Con);
printf("Intelligence Modifier: ");
scanf("%d", aPlayer.Int);
printf("Wisdom Modifier: ");
scanf("%d", aPlayer.Wis);
printf("Charisma Modifier: ");
scanf("%d", aPlayer.Cha);
return aPlayer;
};
And the write bit:
int save_data(){
FILE* PlayerFile = fopen("players.txt","w");
int i = 0;
for (i = 0; i < 1; i++){
struct player_info aPlayer = create_player();
fprintf(PlayerFile, "%s %d %d %d %d %d %d %d\n", aPlayer.name, aPlayer.Level, aPlayer.Str, aPlayer.Dex, aPlayer.Con, aPlayer.Int, aPlayer.Wis, aPlayer.Cha);
}
fclose(PlayerFile);
return 0;
}
Now, to be clear, I can input up to the dexterity modifier. The next line that should ask for the constitution doesn't print, and that's when I get the popup error.
I have tried commenting out everything from the constitution mod down to the charisma just to see, and I get the same problem. Removing just the constitution part doesn't work either. I'm not really sure what's going on here; I've seen other posts saying something about a pointer being wrong, but I don't see anything like that, unless it's just one of those things that you just miss and need someone else to point it out. Anyway, any help is appreciated.

scanf expects the address of the variable you intend to write to. So this
scanf("%d",aPlayer.Level);
Should be this
scanf("%d", &aPlayer.Level);
For all of your stats. The way you have it setup now involves passing an unspecified integral value to scanf (the variable aPlayer.Level and company are uninitialized), which is then reinterpreted as an address that the function attempts to write into. The behavior of of such code is undefined.

Related

How to use char in scanf by using loop?

I want to make simple billing software but I don't know to fix this problem
#include <stdio.h>
int main()
{
char a[20];
int i, j, b;
i = 0;
printf("How many item you have?\n>>> ");
scanf("%d", &j);
for (int i = 0; i < j; i++)
{
printf("Type the name of item no. %d?\n>>> ", i + 1);
scanf("%c", &a);
printf("Type the item quantity?\n>>> ");
scanf("%d", &b);
}
return 0;
}
This code is only for asking questions, as you can see. In this code everything is fine but, when I run this code, the output is:
How many item you have?
>>> 4
Type the name of item no. 1?
>>> Type the item quantity?
>>>
Everything seems fine but I haven't entered the item name and the loop is asking the 2nd question directly. How is it even possible?
The %c format specifier for scanf reads a single character. To read a string (array) of characters, use the %s format specifier. Also, for such arrays, you don't need the & (address of) operator, as the array name itself will 'decay' to a pointer to its first element:
#include <stdio.h>
int main()
{
char a[20];
int i, j, b;
i = 0;
printf("How many item you have?\n>>> ");
scanf("%d", &j);
for (int i = 0; i < j; i++) {
printf("Type the name of item no. %d?\n>>> ", i + 1);
scanf("%19s", a); // The "19" limits input size and allows space for the nul-terminator
printf("Type the item quantity?\n>>> ");
scanf("%d", &b);
}
return 0;
}

Logical issue with printf and scanf

I am revising my basic C to prepare for the upcoming quiz, when i was writing a function to simply take a character input and store it into a struct and print it out again. There is no issue with the compiling whatsoever but i kept getting logical issue. How do i fix this?
#include <stdio.h>
struct player
{
char letter;
int age;
double avg;
};
int main()
{
struct player P1;
char name;
int age;
double avg;
printf("Enter age: ");
scanf("%d", &age);
printf("Enter avg: ");
scanf("%lf", &avg);
printf("Enter name: ");
scanf("%s", &name);
P1.letter= name;
P1.avg = avg;
P1.age = age;
printf("\n Age is: %d \n", P1.age);
printf("Avg is: %lf", P1.avg);
printf(" \n Name is: %c \n", P1.letter);
return 0;
}
If i put in '1' for int, output would be "Age is: 0'
you are trying to get name, age and avg. of the player. so to store name , you should declare an array not a character. and for assigning the name to structure variable use strcpy().(direct assignment not works). OR if you taking only a single character as a name then write scanf like this:
scanf("%c", &name);
check below code, it will help you,
#include <stdio.h>
struct player
{
char letter[10];
int age;
double avg;
};
int main()
{
struct player P1;
char name[10];
int age;
double avg;
printf("Enter age: ");
scanf("%d", &age);
printf("Enter avg: ");
scanf("%lf", &avg);
printf("Enter name: ");
scanf("%s", &name);
strcpy(P1.letter,name);
P1.avg = avg;
P1.age = age;
printf("\n Age is: %d \n", P1.age);
printf("Avg is: %lf", P1.avg);
printf(" \n Name is: %s \n", P1.letter);
return 0;
}
You are using a character data type for entering a string, "char name" which is leading you to undefined behavior.
Instead of that you declare a character array like this "char name[10]" and then read name. but while assigning you have to take care that you can not assign directly you have to use strcpy like this.
strcpy(p1.letter,name) (Here letter is also character array)
Two quick suggestions:
1) Unless you are certain the name buffer will be populated only by short names, (9 or less characters), pick a more reasonable size for the buffer, such as:
char name[100];
This will also require lengthening the member letter in your struct.
2) when using scanf() to read in variables, the address of the variable being read is passed as the 2nd argument. For variables such as int a; or float b; you must use the address of operator: & as a prefix to the variable. But because the variable name of a C string points to the first character in the array, it already is the address of that variable. So you do not need the explicit & operator when reading a C string into the scanf() function. The return value of the function should also be used to determine if the call was successful. Change the following line as shown:
scanf("%s", &name);
int count = scanf("%s", name);//note: use return value of function
// remove & ^
if(count < 0)
{
//handle error
}

C programming Calc

I am trying to make a simple calculator in c as i want to test my programming skills. I keep getting a error though.
#include <stdio.h>
int calc()
{
int *fnum;
int *snum;
printf("Enter your First Number: ");
scanf("%d", fnum);
printf("Enter your Second Number: ");
scanf("%d", snum);
int answer = *fnum + *snum;
printf("%d", answer);
return 0;
}
int main()
{
int *calcType;
printf("Type of Calculation: 1=A, 2=S, 3=M, 4=D: ");
scanf("%d", calcType);
if (*calcType == 1)
{
calc();
}
return 0;
}
But Then i get this error:
Segmentation fault (core dumped)
Please help, i have no idea what this means.
You called scanf to read an integer into the memory pointed to by calcType, but you never set calcType to point to a valid address.
Where the snum and fnum (int * pointers) point to? you have to declare a variable and pass its address (by reference operator &) to scanf.
The code should be something like this
int calc(){
int fnum;
int snum;
printf("Enter your First Number: ");
scanf("%d", &fnum);
printf("Enter your Second Number: ");
scanf("%d", &snum);
int answer = fnum + snum;
printf("%d", answer);
return 0;
}
Also same problem with calcType pointer.
You should be inputing ints, not int* (int pointers):
int fnum; /* This is now an int */
int snum; /* so is this */
printf("Enter your First Number: ");
scanf("%d", &fnum); /* Note that fnum's address is passed */
printf("Enter your Second Number: ");
scanf("%d", &snum); /* Same for snum */
int answer = fnum + snum;
printf("%d", answer);
return 0;
That is a generic error message. You are incorrectly using pointers for fnum and snum, and attempting to add their addresses in memory.
You missed
&
Without it the programm wont know where to storage the data
scanf("%d", &fnum);
I also dont understand why you put
*

C: Array of Structs (Input into int array within array of structs)

Hi I have to create a database that stores students number, name and also stores an array of course marks (1-N) in C Programming Language.
Everything worked until I started coding for the array of course marks. Then every time I compiled the code it kept crashing as soon as it asked to input the course marks.
Can you please tell me where I'm going wrong in my programming for this task? I have attached it to this message.
The program worked for inputting the name, student number, however I could not get the program to input array of marks. I have asked how many course marks to be entered and then used a for loop within the "void insert(void)" function to keep inputting the course marks into the array *marks. I am referring specifically to lines 24 to 30 in my programming code.
Always at this point the program kept crashing and I could not proceed further to enter more names or print the stored student details.
I think there is a problem with this part:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n");
scanf("%d", &(list[num_students].marks[num_marks]));
}
Anyway here is the full code:
#include <stdio.h>
#include <string.h>
struct student{
int number;
char name[10];
int marks[5];
};
struct student list[10];
int num_students = 0;
int num_marks = 0;
int *p;
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++; // HOW DO WE INPUT ARRAY MARKS??? MARK1: , MARK2: , MARK3 ,
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
int main(void)
{
int code;
int opt1;
int courses, i, k, j, counter;
for (;;){
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) DISPLAY REPORT OF ALL STUDENTS: \n");
scanf(" %d", &code);
switch (code){
case 1 :
insert();
break;
case 2 :
printtest();
break;
default:
printf("Illegal code\n");
printf("\n");
}
}
}
Apart from what others pointed out, I'd like to draw your attention towards the following:
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++;
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
There are three problematic statements:
scanf("%s", &list[num_students].name); This is why beginners should use compilers with all warnings enabled.
printf("Mark: %d /100 \n", list[i].marks); What did you declare marks as in the first place?
scanf("%d", num_marks); Seems like you put & operator where not needed and ignore where needed. Read your textbook before asking a question next time.
Seems like you're having a tough time understanding the concept of arrays and pointers. Read your text book thoroughly before venturing into the world of pointers. If you don't use them correctly, even compiler can't help you.
Also, even if I don't expect your program to have a robust input mechanism, at least array bounds checking is expected. Learn good habits from the beginning. They'll save a lot of your time while debugging later.
Seems to be an error in:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
The crash is probably because num_marks as index indexes beyond the array. Change to:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[i]));
}

I can't type all the information in an array of structs

When I try to compile this small program everything is correct but when I run it I find some problems. For example, I can't type the "c" variable in the second element of the table and so on.
#include <stdio.h>
struct point{
char c;
int x,y;
};
int main(void)
{
int size = 4;
struct point tp[size];
for(int i = 0; i < size; i++ )
{
printf("entrer le nom du point no %d: ", i+1);
tp[i].c = fgetc(stdin);
printf("x = ");
scanf("%d", &tp[i].x);
printf("y = ");
scanf("%d", &tp[i].y);
}
}
There are a lots of similar questions here, for example: C scanf() and fgets() problem, fgets doesn't work after scanf.
You could use fgets() for user input and parse string with sscanf() for example.
Or you can use fgetc(stdin); after each scanf() to get rid of '\n' symbol.

Resources