tadm123
tadm123

Reputation: 8787

Initializing a member of a structure with pointers (C)

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.

Upvotes: 2

Views: 3410

Answers (3)

user2857933
user2857933

Reputation: 1

#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

Upvotes: 0

Jason C
Jason C

Reputation: 40315

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.

Upvotes: 2

ddbug
ddbug

Reputation: 1539

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?)

Upvotes: 1

Related Questions