c - Assigning a string to a pointer in a struct -
#include <stdio.h> #include <stdlib.h> #include <string.h> struct person { char *forename; char *surname; int age; }; void change_struct(struct person *person, char *forename, char *surname, int age); void print_struct(struct person *person); int main(void) { struct person person1; person1.forename = malloc((strlen("max") + 1) * sizeof(char)); if (!person1.forename) { exit(exit_failure); } strcpy(person1.forename, "max"); person1.surname = malloc((strlen("mustermann") + 1) * sizeof(char)); if (!person1.surname) { exit(exit_failure); } strcpy(person1.surname, "mustermann"); person1.age = 35; print_struct(&person1); change_struct(&person1, "hans", "bauer", 45); print_struct(&person1); free(person1.forename); free(person1.surname); exit(exit_success); } void change_struct(struct person *person, char *forename, char *surname, int age) { person->forename = realloc(person->forename, (strlen(forename) + 1) * sizeof(char)); if (!person->forename) { exit(exit_failure); } strcpy(person->forename, forename); person->surname = realloc(person->surname, (strlen(surname) + 1) * sizeof(char)); if (!person->surname) { exit(exit_failure); } strcpy(person->surname, surname); person->age = age; } void print_struct(struct person *person) { printf("%s\n", person->forename); printf("%s\n", person->surname); printf("%d\n", person->age); } when assigning string pointer in struct well-defined behaviour if do
person1.forename = "max"; person1.surname = "mustermann"; in main() instead of using malloc() , strcpy()?
note: (of course in specific case need change realloc() calls in change_struct() since undefined behaviour when realloc() receives non- malloc(), calloc(), or realloc() created pointer.)
if dynamic memory allocation should required give explanation why?
as long don't want modify contents,
person1.forename = "max"; person1.surname = "mustermann"; are valid.
in case, person1.forename pointer string literal , attempt modify contents result in undefined behaviour.
that said,
- for
print_struct()function, don't need pass pointer structure. sizeof(char)guaranteed produce1inc. using multiplication (to size inmalloc())is redundant, can omitted easily.
Comments
Post a Comment