Pointers within structures

72 views Asked by At

I am new to c language and I tried to create a structure. so here is the my structure.

typedef struct car{
    int *transmission;
    int *year;
    char color[15];
}CAR;

Then I tried to insert the values to the structure variables using below code,

printf("Enter M Year of car : ");
scanf("%d",car1.year);
printf("Enter color of car : ");
scanf("%s",&car1.color);
printf("Enter transmission type of car (1 for manual & 2 for auto): ");
scanf("%d",car1.transmission); 

But, it returns an error. pls help me to resolve the issue.

2

There are 2 answers

0
pantelis300 On

In this structure you shouldn't declare pointers, but variables

#include <stdio.h>
#include <stdlib.h>

struct car
{
    int transmission;
    int year;
    char color[15];
};

int main()
{
    struct car car1;
    printf("Enter M Year of car: ");
    scanf("%d", &car1.year);

    printf("\nThe year of the car is: %d", car1.year); 

    return 0;
}
0
Horacio On

The problem is that you have not intialized the pointers in your struct with the address of any actual int variables, so they contain garbage.

On the other hand, the color variable is a pointer that DOES point to the first of the 15 chars, therefore you donĀ“t have to pass its address to scanf(), but just its value so that the function can store there the chars read.

Try someting like this:

int aYear, aTransmission;
CAR car1;

car1.year = &aYear;
car1.transmission = &aTransmission;

printf("Enter M Year of car : ");
scanf("%d",car1.year);
printf("Enter color of car : ");
scanf("%s",car1.color); /* color IS a pointer */
printf("Enter transmission type of car (1 for manual & 2 for auto): ");
scanf("%d",car1.transmission);

This code will store the values into the extern variables aYear and aTransmission, which are pointed by the pointers into the struct.