Doubt in Struct + C pointer

2

Given 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]); 
}
    
asked by anonymous 29.07.2014 / 20:01

2 answers

1

So far I do not understand what I wanted to do with

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

But if you replace with this, you will have the registration:

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

Note that enrollment is int .

    
29.07.2014 / 20:58
1

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

Because Param is a 12-element struct, when you do a pointer arithmetic , for each unit you add, you add 12 elements. So you were actually adding 48 positions (12 *% with%).

So, to execute correctly, you have to transform this struct of 12 elements into a pointer to char, which has 1 byte. And to use printf as a float, you have to, after arithmetic with pointer, turn pointer to char in pointer to float.

It looks like this:

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