0
hey hi everyone could you pls help me with my code it doesn't printing rollnum
#include <stdio.h> int main() { char fname[110],sname[120],phn[130],rollnum[105],gender[1]; printf("enter first name\n"); scanf("%s",fname); printf("enter second name\n"); scanf("%s",sname); printf("enter nume\n"); scanf("%s",phn); printf("enter roll number\n"); scanf("%s",rollnum); printf("enter your gender either M or F\n "); scanf("%s",gender); //printing your details printf("\n"); printf("hey! %s ",fname); printf("%s\n",sname); printf("\ncontact%s",phn); printf("your RollNmber is %s",rollnum); printf("gender:%s",gender); }
1 Respuesta
+ 3
Saitheja Komalla
Change definition `gender[1]` to `gender[2]`.
Whenever you want to store a string in a char array, you have to allocate one extra space for the null character '\0'. If you don't define the array with enough space and try to store a string inside it (e.g. gender), the null character gets written into memory but outside of the bounds of that array and possibly into another array or variable. This is infamously known as a buffer overflow problem, and can cause all sorts of corrupted data issues.
In this case, I suspect that when you entered all the input values, the last null char got written out of the bounds of the gender array and into the rollnum array. You can check this (before the fix) by entering all the values except for gender and will notice that rollnum prints.