Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a struct with a string member in C

I have a simple struct containing a string defined as a char array. I thought that copying an instance of the struct to another instance using the assignment operator would simply copy the memory address stored in the char pointer. Instead it seems that the string content is copied. I put together a very simple example:

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

struct Test{
  char str[20];
};

int main(){

  struct Test t1, t2;
  strcpy(t1.str, "Hello");
  strcpy(t2.str, "world");
  printf("t1: %s %p\n", t1.str, (char*)(t1.str));
  printf("t2: %s %p\n", t2.str, (char*)(t2.str));
  t2 = t1;
  printf("t2: %s %p\n", t2.str, (char*)(t2.str));
  return 0;
}

Compiling this code with gcc 4.9.2 I get:

t1: Hello 0x7fffb8fc9df0
t2: world 0x7fffb8fc9dd0
t2: Hello 0x7fffb8fc9dd0

As I understand, after t2 = t1 t2.str points to the same memory address it pointed before the assignment, but now inside that address there is the same string found inside t1.str. So it seems to me that the string content has been automatically copied from one memory location to another, something that I thought C would not do. I think that this behaviour is triggered by the fact that I declared str as a char[], not as a char*. Indeed, trying to assign directly one string to another with t2.str = t1.str gives this error:

Test.c: In function ‘main’:
Test.c:17:10: error: assignment to expression with array type
   t2.str = t1.str;
      ^

which makes me think that arrays are effectively treated differently than pointers in some cases. Still I can't figure out which are the rules for array assignment, or in other words why arrays inside a struct are copied when I copy one struct into another one but I can't directly copy one array into another one.

like image 386
Nicola Mori Avatar asked Dec 14 '22 14:12

Nicola Mori


1 Answers

The structure contains no pointer, but 20 chars. After t2 = t1, the 20 chars of t1 are copied into t2.

like image 87
Michel Billaud Avatar answered Jan 01 '23 01:01

Michel Billaud