String help!

Norman Diamond ndiamond at watdaisy.UUCP
Wed Mar 13 14:23:40 AEST 1985


> Hmmm... According to some of the advice here, the following is not
> an acceptable way to declare an initialized array:
> 
> 	char *fup = "0123456789";
> 
> The reason is that some C compilers are likely to take the string 
> constant and put it into a read-only portion of memory.

fup is not read-only.  The string might be.

> Instead,
> if we want an initialized character array, we are supposed to say 
> something like:
> 
> 	char fup[11];	/* I hope this isn't read-only */

The array fup is not read-only.

> 	int  i;
> 	...
> 	for (i=0; i<11; i++)
> 	    fup[i] = i + '0';
> 	fup[i] = '\0';
> 
> or maybe:
> 
> 	char *fup;
> 	int  i;

Yup, this time you gotta do it.

> 	...
> 	fup = malloc(11);

... proving that fup is not read-only ...

> 	if (fup == NULL) {	/* Gotta check for failure */
> 	    fprintf(stderr,"Out of space, can't get 11 bytes\n");
> 	    perror("foo");
> 	    exit(17);
> 	}
> 	for (i=0; i<11; i++)	/* Initialize the sucker */
> 	    fup[i] = i + '0';
> 	fup[i] = '\0';
> 
> To this, I say "NONSENSE".

It is nonsense, all right.  Try:

   char fup[11] = "0123456789";

This is not the same as assigning a pointer to address a read-only item.
This initializes the contents of the writable array fup.

-- 

   Norman Diamond

UUCP:  {decvax|utzoo|ihnp4|allegra}!watmath!watdaisy!ndiamond
CSNET: ndiamond%watdaisy at waterloo.csnet
ARPA:  ndiamond%watdaisy%waterloo.csnet at csnet-relay.arpa

"Opinions are those of the keyboard, and do not reflect on me or higher-ups."



More information about the Comp.lang.c mailing list