Hi experts,
I'm from a Verilog HDL background and trying to learn C. There are a lot of similarities between Verilog and C but the concept of char arrays and strings has me confused. I'd appreciate any help or pointers here.
This is the code, nothing fancy, just basic experiments around char array and string,
#include <stdio.h>
#include <string.h>
int main() {
char test1[5];
char test2[5];
int i;
test[0] = 'a';
test[1] = 'b';
test[2] = 'c';
test[3] = 'd';
test[4] = 'e';
test[5] = 'f';
strcpy (test2, test1);
for (i = 0; i < 6; i = i + 1)
printf("%c\n", test2[i]);
return(0);
}
I was expecting this code to fail during compilation (I'm using GCC version 3.2.3 on RHEL 3.0) because I'm exceeding the array bounds with the assignments. What is more surprising to me is that all the characters (a-f) do get printed. Any ideas why? The program output is this,
[nageshg@lx-nageshg mywork]$ a.out
a
b
c
d
e
f
[nageshg@lx-nageshg mywork]$
Another doubts is, what about the null terminating character in this case? I read that if a char array is initialized like this,
char test1[5] = "test";
the last (unassigned) character is set to '\0' and this variable becomes a string as opposed to just an array of characters. But if I initialize it character by character (as I did in the program above), I have to take care to set the last character to '\0' myself. Moreover it is said that the string handling functions expect a null terminated string as their arguments. But in the code above, this doesn't seem true. So why does strcpy() work?
I guess my basic doubt here is, what is the difference between an array of characters and a string in C? Or is it that they are one and the same thing, regardless of how I initialize and whether or not the last character is set to '\0'?
This essential point seems to have been deliberately evaded in the book I'm reading (or I may be missing the point myself). Please help.
BTW, if I remove the for loop in the code above and use the printf with the string format specifier,
printf("%s\n", test2);
I see abcdef as the output.
Thanks,
Nagesh
P.S. I did search the forum before deciding to post this. There doesn't seem to be anything dealing directly with something this basic.