newbie print struct C programming question
I am new in C programming, and trying to create simple code below for printing a struct member using other function.
I do not understand this, as in the function funct_to_print_value, I already declare the struct variable "car", and开发者_高级运维 I believe what I need is just to print is using (dot) notation to access it. Appereantly not, as I got the error above. Does anyone can share their knowledge, how I can print the value of buyer, and what mistake I had done above?
Thank you ..
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct slot_car {
int buyer;
} slot_car;
int main() {
slot_car car;
memset(&car, 0, sizeof(car));
car.buyer = 1;
printf("value of car is .. %d\n", car.buyer);
funct_to_print_value();
printf("end of function..\n");
return 0;
}
int funct_to_print_value()
{
printf("you are in printlist function..\n");
slot_car car;
printf("value of car inside is %d\n", car.buyer);
return 1;
}
Since you declared car inside each function separately, they are separate (local) variables. You probably want to pass it from main to funct_to_print_value as a parameter instead. The warning is strange, but it is possible that the compiler detected the uninitiated value and gave this message because it is first used in printf.
This looks fine to me. It would be helpful to have more information. All I did was extract your example into a temp.c file and compile it using gcc -c temp.c. There were no errors.
On which OS is this?
Which build environment/compiler is this?
How are you building this? (commands used in the build environment)
I'm using gcc 4.4.3 on Ubuntu Linux 10.04.
Edit 1:
What happens if you cast car.buyer to an int?
printf("value of car is .. %d\n", (int ) car.buyer);
Edit 2:
How about this to print your 1?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct slot_car {
int buyer;
} slot_car;
int main() {
slot_car car;
memset(&car, 0, sizeof(car));
car.buyer = 1;
printf("value of car is .. %d\n", car.buyer);
{
int temp_ret;
temp_ret = funct_to_print_value();
printf("end of function..%d\n",temp_ret);
}
return 0;
}
int funct_to_print_value()
{
printf("you are in printlist function..\n");
slot_car car;
printf("value of car inside is %d\n", car.buyer);
return 1;
}
value of car is .. 1
you are in printlist function..
value of car inside is 134514096
end of function..1
cnorton@steamboy:~/scratch$
精彩评论