harianja
harianja

Reputation: 63

pointer to struct in C

I'm learning pointer to structure in c and i've made this code for learning :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
   int id;
   char *name;
}struct_type_t;

void set_struct(struct_type_t **);

int main(int argc, char *argv[])
{
     struct_type_t *m = NULL;

     set_struct(&m);

     printf("%d\n", m->id);
     //fflush(stdout);
     printf("%s\n", m->name);
     return 0;
 }

 void set_struct(struct_type_t **m)
 {
      struct_type_t t;
      *m = &t;

      (*m)->id = 5;
      (*m)->name = "Pointer To Structure";
 }

The function set_struct is meant to set the struct members by passing the address of pointer to structure struct_type *m to the function.

but in the printf line in the main function, it's not print the string member name of structure, instead it only print the integer member id.

I have used fflush to, but still not working.

please help me to correct this code and check what's wrong....

Upvotes: 1

Views: 421

Answers (2)

Bruno Sautron
Bruno Sautron

Reputation: 43

Your *m is a pointer and is equal to NULL. So use malloc to have a pointer to your struct_type_t that you can free it after.

void set_struct(struct_type_t **m)
{
    *m = (struct_type_t *)malloc(sizeof(struct_type_t));
    (*m)->id = 5;
    (*m)->name = strdup("Pointer To Structure");
    // or: (*m)->name = "Pointer To Structure";
}

Upvotes: 0

George Sovetov
George Sovetov

Reputation: 5218

You return pointer to local object. It's created on stack. You shouldn't use it after function finishes its work because it doesn't exist anymore and its memory may contain other objects.

Allocate chunk of memory on heap using malloc, initialize it and use it until you call free on it.

Upvotes: 0

Related Questions