2

I'm a begginer and have been reading books on C, I have a question about pointers of structures. Below I tried to initialize members of the structure using a "*p" pointer

#include <stdio.h>

struct part{
int num;
char *name;
};

int main()
{
   struct part *p;    //creating a pointer with 'struct part' type

   p->num= 5;          //initializing
   p->name= "Jose";

   printf("%d\n",p->num);
   printf("%s",p->name);

   return 0;
}

Probably a dumb question but I'm interest to know why is it wrong? The program is crashing obviously.

tadm123
  • 8,294
  • 7
  • 28
  • 44

3 Answers3

2

You declared a pointer but it doesnt point to anything.

You'd have to do e.g. p = malloc(sizeof(struct part)) or maybe struct part q; p = &q; or otherwise set it to point to something first.

Check out the C version of this old classic.

Jason C
  • 38,729
  • 14
  • 126
  • 182
  • thanks for the help. Can I ask you as question.. When you set your pointer to a type 'struct part', wouldn't this information make the compiler know how much space in memory your pointer variable will occupy? why would you need to explicitly do malloc? – tadm123 Aug 30 '16 at 03:18
  • @tadm123 Before I answer that: Did you watch the video? – Jason C Aug 30 '16 at 03:19
  • Ok just watched it. I see now, I guess they are pointing at nothing and you can't give values to nothingness.. thanks, good video too lol – tadm123 Aug 30 '16 at 03:28
  • Would this be fair? p=malloc(sizeof(*p)) – tadm123 Aug 30 '16 at 03:34
  • @tadm123 Exactly. And yeah that videos great, lol. Your pointer variables actually do have a size themselves, they are really just memory addresses, and their size is equal to whatever the size of a memory address is on that platform (e.g. 4 bytes on a 32 bit system). You can see this if you use sizeof on one. But unless they contain a valid address of *something*, you can expect binky to die a painful death when you dereference them. – Jason C Aug 30 '16 at 03:35
  • 1
    @tadm123 Yeah that works although it's kinda strange, at least imho. It's a bit more idiomatic to use `sizeof(your type)`. But I'm sure you can find opinions both ways. It does work though. – Jason C Aug 30 '16 at 03:39
1

The pointer is not initialized. It does not point to a valid memory so you cannot reference struct members thru it. Do something like

struct part *p = malloc(sizeof(struct part));

(if this is the actual example in this C book - look for a better book?)

ddbug
  • 1,392
  • 1
  • 11
  • 25
  • Nope it is just me trying doing trial/error of the concepts writing different codes. Appreciate the help though, I can see why now. – tadm123 Aug 30 '16 at 03:09
0
#include <stdio.h>  
#include <stdlib.h>

struct part 
{
  int num;
  char *name;
};

int main()
{

struct part *p = (struct part*)malloc(sizeof(struct part)); //memory allocation

p->num = 5;
p->name = "Jose";          //initializing

printf("%d\n", p->num);
printf("%s", p->name);

return 0; }

Try this out