user1363410
user1363410

Reputation: 135

pointers to structs versus malloc in C?

#include<stdio.h>

typedef struct telephone
{
    char *name;
    int number;
} TELEPHONE;

int main()
{
    //TELEPHONE index;
    TELEPHONE *ptr_myindex;
    ptr_myindex = (TELEPHONE*)malloc(sizeof(TELEPHONE)); 
    //ptr_myindex = &index;

    ptr_myindex->name = "Jane Doe";
    ptr_myindex->number = 12345;
    printf("Name: %s\n", ptr_myindex->name);
    printf("Telephone number: %d\n", ptr_myindex->number);

    free(ptr_myindex);

    return 0;
}

When I compile this, it outputs the same result as when I don't dynamically allocate the pointer to the struct, and instead use the part in my code that has been commented out. Why does this happen?

Upvotes: 0

Views: 147

Answers (2)

Zagorax
Zagorax

Reputation: 11890

When you declare:

TELEPHONE index

The compiler knows what kind of struct TELEPHONE is and so it allocates the memory needed by that struct.

For example:

int a = 5;
int *p = &a;

It's perfect. But if we want to achieve the same without int a = 5, we should do the following:

int *p;
p = (int*)malloc(sizeof(int));
*p = 5;

There's a difference tough. The first code allocate the variable in the stack, while the second code allocate it in the heap. But in the second case, there's no allocated space for the struct before the malloc, and the only allocated space is for the pointer itself (that do not need the same space as the struct itself).

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 613262

Your two versions of code do the following:

  1. Allocate the struct on the heap.
  2. Allocate the struct as a local variable.

These options are interchangeable in this program. The code that assigns to the struct, and then prints, doesn't care whether the struct was heap allocated or is a local variable.

Upvotes: 2

Related Questions