0

So I wanted to be better at pointers in C, so I try to use them in structures, functions and stuff, but in this simple example I'm having a weird problem, I think it has to do with the ordering So I respected the order as in the structure while using printf, but still it gives me 'segmentation fault' with no compiling errors, please help me !

-Here is the code :

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct 
{
    float *dbl;
    int *age;
    
} Coordonnees;

int main()
{
    Coordonnees joueur;
    
    *joueur.dbl= 12;
    *joueur.age= 13;
   printf("dbl= %f ",*joueur.dbl);
   printf("Age=  %d",*joueur.age);

    return 0;
}

-but Doing only this works fine and prints "dbl=12.0000" :

    #include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct 
{
    float *dbl;
    int *age;
    
} Coordonnees;

int main()
{
    Coordonnees joueur;
    
    *joueur.dbl= 12;
    
   printf("dbl= %f ",*joueur.dbl);

    return 0;
}


 
  • You have three attemts to answer why these statements *joueur.dbl= 12; *joueur.age= 13; invoke undefined behavior. – Vlad from Moscow Jul 05 '21 at 13:29
  • 1
    The first part of the linked duplicate answer says it all: "A pointer is a special type of variable, which can only contain an address of another variable. It cannot contain any data. You cannot "copy/store data into a pointer" - that doesn't make any sense. You can only set a pointer to point at data allocated elsewhere." – Lundin Jul 05 '21 at 13:33
  • Yes but why the second code is working ? and I learned that adding * to the pointer is enough to store data to that variable – Youssef Kessas Jul 05 '21 at 17:39

0 Answers0