Doubt in Struct + Pointer in C

Asked

Viewed 306 times

2

Considering the code below, I wonder why the second printf of the Lealuno procedure does not print correctly?

#define MAX 3
typedef struct aluno{
    int matricula;
    float notas[2];
} Aluno ;
int t=1;
void LeAluno(Aluno *Param){// com ponteiro
    t++;
    Param->matricula=10*t;
    Param->notas[0]=20*t;
    printf("\n 1   %f",(*Param).notas[0]);
    printf("\n 2   %f",*(Param+sizeof(int)) ); //size of int matricula;
    Param->notas[1]=30*t;
}
void main(){
    int i;
    Aluno Turma[MAX];
    for(i=0; i< MAX; i++)
        LeAluno(&Turma[i]); 
}
  • Printfs are: printf(" n 1 %f",(Param). notes[0]); printf(" n 2 %f",(Param+sizeof(int)) );

  • 2

    Explain what you want to show with prints

  • To access members of a structure via a pointer you can use the shortcut -> -- (*Param).notas[0] is the same as Param->notas[0]

2 answers

1

If I understand correctly, you are wanting the second printf to have the same result as the first printf.

How Param is a 12 element struct, when you make a pointer arithmetic, for each unit you add up, you add up 12 elements. Therefore, in fact you were adding up 48 positions (12*sizeof(int)).

So, to run correctly, you have to turn this 12-element struct into a char pointer, which is 1 byte. And to use the printf as a float, you have to, after the pointer arithmetic, turn the char pointer into a float pointer.

Stay like this:

printf("\n 2   %f",*(float *)((char *)Param+sizeof(int)) ); //size of int matricula;

1

So far I don’t understand what you wanted to do with

printf("\n 2 %f",*(Param+sizeof(int)) ); //size of int matricula;

But if you replace it with that, you’ll have the license plate:

printf("\n 2 %d",(*Param).matricula );

Note that the license plate is int.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.