2

Possible Duplicate:
How to create an array of string in C?

In my Last question I wrote the following lines of code

#include <stdio.h>
int main(void){
  char str1[] = {'f','i'};
  char str2[] = {'s','e'};
  char str3[] = {'t','h'};
  char *arry_of_string[] = {str1,str2,str3};
  printf("%s\n",arry_of_string[1]);
}  

thanks to people points out I should at the '\0' at the end of the string. I learned the right way to do this. I'm curious about result of the faulty code:

sefi

I remember from the C reference book, pointer looking for the '\0' I think without the \0 terminator, it the result should be:

seth because str3 is the next element in the array. Anyone can explain why is it in term of the internal structure of array?

Community
  • 1
  • 1
mko
  • 21,334
  • 49
  • 130
  • 191
  • This is the same question, you were given code in that question which showed correct use. Re-read that question and change that question. However, it seemed very clear to me. – Hogan Jul 27 '12 at 12:37
  • You need to add \0 at the end, because (i think, but im not familiar with c) function will print everything until it acieve \0. So if it printed sefi, its just lucky found \0 at the end. Maybe try add str4, str5 and test it? Maybe these strX are in different order stored? – apocalypse Jul 27 '12 at 12:41

1 Answers1

0

C does not make any guarantees about the order of variables in memory. It does however guarantee that struct members are laid out in memory in sequence, with the first member at offset 0 of the struct.

So what you are doing is testing undefined behavior, which may change any time with the compiler version, compile options, or even the phase of the moon. Don't rely on undefined behavior. Don't go reverse engineering your compiler. It is mostly useless knowledge that will be outdated before your resume grows too much longer and will only cause surprises in the future when you have to deal with other compilers.

If you want to know how C works, read the only authoritative source, the ISO C Standard. Accept no substitute (other than maybe, Kernighan, Ritchie, "The C Programming Language, 2nd ed.")

Jens
  • 69,818
  • 15
  • 125
  • 179