Hello and thanks in advance,
In short, what I do is create a pointer which creates a local variable on the Stack and then I request memory by malloc which allocates space in the heap.
Then I create a local int on the stack.
Then I request users input through scanf.
But upon entering the last digit, the console vanishes and does not print me the result even if I try to hold it through getchar()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 80
int main()
{
char *student = malloc(MAX_LINE * sizeof(char));
int grade;
printf("Enter students name ");
scanf("%s", student);
printf("Enter students grade ");
scanf("%d", grade);// i would say it has to be grade and not &grade
// it vanishes right after here. Cant get to see any result
printf("%s received a %d\n", student, grade);
free(student);
getchar();
}
scanf("%d", grade);should bescanf("%d", &grade);You should pass the address of the variable/buffer where you want to store the input element. And
graderefers to the content, there the&addressof operator operating ongrade&gradegives us the address of the variable.In case of
scanf("%s", student);thestudentitself refers to the address , ie the contents of the pointer variablestudentwhich contains the base address of the memory block you just allocated. Therefore this is correct.The arguments should always point to the address of the location of the variable/buffer where you want
scanfto put that particular section of that input.Say initially you have the garbage
0x5964stored ingrade, and the memory address ofgradeis0x1234abcd. Inscanf ("%d", grade);,scanfwould try to write the read in integer into the memory location0x5964, which is invalid.Whereas in
scanf ("%d", &grade);,scanfwould store the read in integer into the memory location0x1234abcd. After this referring togradeas r-value would get you the contents on the memory location0x1234abcd, this is what you want.