LinuxSA Mailing list archives

Index: [thread] [date] [subject] [author] [stats]
  From: <iwrigb@tpg.com.au>
  To  : <linuxsa@linuxsa.org.au>
  Date: Thu, 2 Nov 2000 04:04:50 GMT

Re: C code

Hi,
  the difference is that the {} syntax is used for initialising 
arrays, and can be used for arrays other than just character arrays. 
the "" syntax is a special case for character arrays, that as you 
have noticed behaves similarly to the {} syntax with characters.

On the other hand a pointer is not an array. Therfore the {} syntax 
will not work, and the "" syntax behaves diferently ie:

char *p = "whatever";

this allocates space for the pointer p, and creates a constant array 
of characters with a value equal to {'w', 'h' ..., 'r', '\0'} and 
then initialises p with the address of the constant char array. This 
is bad if you want to change the values of the characters, as the 
memory that is pointed to is constant and should not be changed, this 
is NOT the same as doing this, which allows the characters to be 
changed:

char *p;
p = new char[strlen("whatever") + 1];
strcpy(p, "whatever");

this allocates memory for the pointer p and then allocates memory for 
an array of 9 characters and puts its address in p, and finally 
copies the charecters 'w', 'h', ... 'r', '\0' into that array. This 
is much closer in operation to:

char c[9] = "whatever";
//or char c2[9] = {'w', 'h', ..., 'r', '\0'}

HTH
Barney

-- 
LinuxSA WWW: http://www.linuxsa.org.au/  IRC: #linuxsa on irc.linux.org.au
To unsubscribe from the LinuxSA list:
  mail linuxsa-request@linuxsa.org.au with "unsubscribe" as the subject


Index: [thread] [date] [subject] [author] [stats]
Return to the LinuxSA Mailing List Information Page