initialization of character arrays

Leonard Sitongia sitongia at hao.ucar.edu
Wed Nov 30 00:36:12 AEST 1988


System:                 Sun-4/280S
OS:                     4.0
Name:                   Leonard Sitongia
Company:                High Altitude Observatory / NCAR

The declarations of arrays using pointers or braces are supposed to be the
same, because the name of an array is the pointer to it.  [[ No, they're
not.  In one case the pointer's value is a variable and in the other it is
a constant.  --wnl ]]

	char *array;
	char array[];

The compiler doesnt treat definition of these the same when initialization 
of character arrays is involved.  Here is a sample program:
__________

char arr1[] = "array1";
char *arr2 = arr1;
char arr3[] = arr1;

main ()
{
	printf("array1 = %s  array2 = %s array3 = %s\n",arr1,arr2,arr3);
	}
__________

It produces these error messages:
"bozo.c", line 3: warning: illegal combination of pointer and integer, op =
"bozo.c", line 3: warning: shortening &arr1 may loose significance
"bozo.c", line 3: illegal initialization
"bozo.c", line 3: warning: empty array declaration

Line two is ok, but line three is not.

This problem comes up in the context of using xstr to produce shared
strings for files that have the RCS's suggested header initializations.

Is this a bug or am I misunderstanding something?  Where is the integer
that the first compiler warning refers to above?

[[ You are misunderstanding something.  The declarations 'char *a' and
'char a[]' are very different.  The first is declaring a pointer to a
character and the second is declaring an array of characters.  I think of
it in the following way:  'char *a' is setting aside enough space for a
character pointer and calling that space "a", but 'char a[X]' is setting
aside X characters and creating a *compile-time constant* called "a" that
points to the first element of the array.  In the case of
'char a[] = "abcd"', the size of the array (the "X" value) is determined
by the initialization string.  Thus the declaration 'char *a = b;' is
invalid because you are trying to change the value of a compile-time
constant, "a".  The only time that 'char *a' and 'char a[]' are
identical is when 'a' is a formal parameter for a function.  --wnl ]]

Thanks,

-Leonard E. Sitongia    System Programmer		 (303) 497-1509
USPS Mail: High Altitude Observatory P.O. Box 3000 Boulder CO  80307
Internet:               sitongia at hao.ucar.edu
SPAN:			NSFGW::"hao.ucar.edu!sitongia"	[NSFGW=9580]



More information about the Comp.sys.sun mailing list