问题
Let's say for example, I have a struct:
typedef struct person {
int id;
char *name;
} Person;
Why can't I do the following:
void function(const char *new_name) {
Person *human;
human->name = malloc(strlen(new_name) + 1);
}
回答1:
You need to allocate space for human
first:
Person *human = malloc(sizeof *human);
human->name = malloc(strlen(new_name) + 1);
strcpy(human->name, new_name);
回答2:
You have to allocate memory for the structure Person
. The pointer should point to the memory allocated for the structure. Only then you can manipulate the structure data fields.
The structure Person
holds id,
and the char
pointer name
to the name. You typically want to allocate memory for the name and copy the data into it.
At the end of the program remember to release memory for the name
and the Person
.
Release order is important.
Small sample program to illustrate the concept is presented:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct person {
int id;
char *name;
} Person;
Person * create_human(const char *new_name, int id)
{
Person *human = malloc(sizeof(Person)); // memory for the human
human->name = malloc(strlen(new_name) + 1); // memory for the string
strcpy(human->name, new_name); // copy the name
human->id = id; // assign the id
return human;
}
int main()
{
Person *human = create_human("John Smith", 666);
printf("Human= %s, with id= %d.\n", human->name, human->id);
// Do not forget to free his name and human
free(human->name);
free(human);
return 0;
}
Output:
Human= John Smith, with id= 666.
来源:https://stackoverflow.com/questions/26310513/why-cant-i-dynamically-allocate-memory-of-this-string-of-a-struct