Matt Hall
Matt Hall

Reputation: 330

using strcpy to copy a string to a member of a structure via the pointer operator

I'm trying to use strcpy to set values for a char array which is the member of a structure. I want to do this using the pointer operator if possible.

struct my_struct{
  char foo[15];
} *a_struct_Ptr;

int main(){
  strcpy(a_struct_Ptr -> foo, "test");
return 0;
}

I can compile this code but when I go to run it I get a segmentation fault.

Also it seems to work fine if I don't define the struct as a pointer, for example the following code works fine...

struct my_struct{
  char foo[15];
}a_struct;

int main(){
  strcpy(a_struct.foo, "test");
  return 0;
}

I want to be able to do this with pointers though. Any feedback is appreciated. Thanks

Upvotes: 1

Views: 11191

Answers (1)

Matt Hall
Matt Hall

Reputation: 330

The problem as many commented, was that I didn't allocate memory for the pointer to my structure.

By preceding my strcpy statement with

a_struct_Ptr = (struct my_struct *) malloc(sizeof(struct my_struct));

I was able to successfully copy a string literal to the char array member of my_struct.

As is good practice, I added free(a_struct_Ptr); after the struct is done being used.

Upvotes: 3

Related Questions