-1
#include <stdio.h>
typedef struct TESTCASE{
    char *before; 
}ts;
int main(void) {
     ts t[2] = {{"abcd"}, 
                {"abcd"}};
     t[0].before[0] = t[0].before[2] = t[0].before[3] = 'b';
     printf("%s - %s\n", t[0].before, t[1].before);
     return 0;
}

the output is

bbbb - bbbb

I compile with gcc in Cygwin

cc -g test.c -o test

my question is, with what compile option, I can reap a result of bbbb - abcd?

Weida
  • 115
  • 1
  • 5
  • Didn't the daemons coming out of your nose hurt? –  Sep 20 '12 at 13:57
  • This question appears to be off-topic because it is a duplicate (but finding the duplicate is hard) and because it is unlikely to help other people in the future. – Jonathan Leffler Mar 03 '14 at 03:05

2 Answers2

5

You are not supposed to write the strings, they are "immutable", writing to it results in undefined behaviour.

Because of that, the compiler is free to use the same location for both strings.

Hint: strdup() - what does it do in C?

Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
0

t[0].before[3] = 'b'; will do a segmentation fault on some systems. You can't write into a constant string.

#include <stdio.h>
typedef struct TESTCASE{
  char before[5];
}ts;
int main(void) {
  ts t[2] = {{ {'a','b','c','d',0} },
             { {'a','b','c','d',0} }};
  t[0].before[0] = t[0].before[2] = t[0].before[3] = 'b';
  printf("%s - %s\n", t[0].before, t[1].before);
  return 0;
}
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36