简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM