in a struct, scanf returns var address not value
I tried to print the value of an int variable of a struct but it prints out the address instead.. don't know why, here is the code:
struct data{ char name[20]; int age[100]; }; typedef struct data dataobj; int main() { dataobj element; printf("enter a name:n"); gets(element.name); printf("name is: %sn",element.name); printf("enter a number:n"); scanf("%d",&element.age); printf("number is: %d",element.age); return 0; }
output here:
enter a name: John name is: John enter a number: 30 number is: 6356352 Process returned 0 (0x0) execution time : 7.278 s Press any key to continue.
You can see it doesn't print 30 as I wanted to, instead it prints 6356352 (which should be the address of element.age var)
I don't think you mean to have the age
property as an array of 100 int
s; in the case that you don't, if you change your struct
definition to only have a single int
:
struct data{
char name[20];
int age;
};
the code you provided works just fine. If you're looking to bound the value of age, you wouldn't want to do so using an array. Using an array like that implies each dataobj
is described by a name and 100 ages. Instead, consider adding a run-time check such as:
if (element.age < 0 || element.age > 99) {
printf("Bad age valuen");
}
Don't use gets
, is deprecated in C99 and removed from C11
Instead, use fgets
:
char *ptr;
fgets(element.name, sizeof element.name, stdin);
/* Remove the trailing newline */
ptr = strchr(element.name, 'n');
if (ptr != NULL) {
*ptr = ' ';
}
And age
is not an int
but an array of int
s:
struct data{
char name[20];
int age[100];
};
change
scanf("%d",&element.age);
printf("number is: %d",element.age);
to
scanf("%d",&(element.age[0]));
printf("number is: %d",element.age[0]);
in order to read into the age's 1st element (sitting at index 0), or simply use a plain int
instead of an array
in your code consider this statement.
scanf("%d",&element.age);
Here, age is of type array size 100 integer elements. So inside your memory a series of 100 integers was created and the address of starting element is stored in other pointer variable(int your case age). So, when you are scanning value, you are trying to manipulate the base address of your array which is not possible. This comes under logical error which can be traced only by understanding. So, just remember one thing.
int age[100]
this is a declaration in which compiler creates a pointer and 100 integer variables(contiguous). And the address of first variable is stored in pointer which takes name given to array.
So, when you are trying to print it it is printing the base address array age[100].
链接地址: http://www.djcxy.com/p/72198.html上一篇: while循环来验证输入是C中的数字吗?
下一篇: 在一个结构中,scanf返回的是无效地址