-6

My program does not print anything and fails.

#include <stdio.h>

struct data{
int giorno, mese, anno;
};
struct data d, *p;

int main(void){ 

    p->giorno = 15;
    p->mese = 8;
    p->anno = 2005;
    printf("%d", p->giorno );
}

OUTPUT:

Process exited after 0.2837 seconds with return value 3221225477 Press any key to continue. . .

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 6
    `p` is a pointer to **what**? – Evg May 13 '21 at 07:57
  • A few links that provide basic discussions of pointers may help. [Difference between char *pp and (char*) p?](https://stackoverflow.com/a/60519053/3422102) and [Pointer to pointer of structs indexing out of bounds(?)...](https://stackoverflow.com/a/60639540/3422102) (ignore the titles, the answers discuss pointer basics) – David C. Rankin May 13 '21 at 08:02

2 Answers2

0

The variable p doesn't point to anywhere. The memory there is just garbage value. So, either do:

p = malloc(sizeof(struct data));

This will allocate some memory on the heap and store the address in p.

Or,

p = &<some valid memory>;

I think you intended to do:

p = &d;

Which would store the address of d in p.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shambhav
  • 813
  • 7
  • 20
0

If your intention is to put data in a struct there isn't any need for a pointer. Just use:

#include <stdio.h>

struct data{
    int giorno, mese, anno;
};
struct data d;

int main(void){

    d.giorno = 15;
    d.mese = 8;
    d.anno = 2005;
    printf("%d", d.giorno);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131