2

I am trying to modify a field inside a struct. I have no trouble doing this with other types (i.e. int, float etc.) but char * is giving me problems. I think I have to do something like:

typedef struct{
    char *string_field;
} struct_name;

struct_name *struct_name1;
struct_name1 = (struct_name *) malloc(sizeof(struct_name));
strcpy(struct_name1->string_field, new_string);

printf("New string: %s\n", struct_name1->string_field);

But this gives me a segmentation fault. What reason do you think I would get this problem for? Initially, I thought maybe the char *string_field was not big enough to copy to, but I changed the size of it manually to be of size 100 (more than enough) and I still get this problem.

GCC
  • 21
  • 1
  • 2

2 Answers2

4

You reserve memory for your struct, which comprises a pointer to a string, but not the space for a string's content. Reserve memory for the string content and let your struct's pointer point to it; then you can copy newstring's content into that memory:

struct_name1->string_field = malloc(strlen(new_string)+1);
strcpy(struct_name1->string_field, new_string);
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

Allocate memory for the structure as well as for the string. In example below there is a room for 63 characters in the string. Remember to free the allocated memory.

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

typedef struct{
    char *string_field;
} struct_name;

int main()
{
   struct_name *struct_name1;
    struct_name1 =  malloc(sizeof(struct_name));
    struct_name1->string_field = malloc(64*sizeof(char));

    strcpy(struct_name1->string_field, "new_string");

    printf("New string: %s\n", struct_name1->string_field);

    free(struct_name1->string_field);
    free(struct_name1);

    return 0;
}

OUTPUT:

New string: new_string
sg7
  • 6,108
  • 2
  • 32
  • 40