[Techtalk] C Programming Question

Malcolm Tredinnick malcolm at commsecure.com.au
Wed May 29 14:37:56 EST 2002


On Wed, May 29, 2002 at 02:32:10PM +1000, Malcolm Tredinnick wrote:
> On Wed, May 29, 2002 at 12:18:25PM +0800, Sujita Purushothaman wrote:
> > Hi,
> >     I'm having a problem with pointer-to-array in C.
> > I have to use the structure char  *somename[ ] . I also
> > need to store/assign data to the strings halfway thro the
> > program. ( I know I can initialise it as :
> > char  *somename[ ] = {"data1","data2"}; etc.
> > At some point in the program I need to change "data1"
> > to "somethingelse1" . How do I do that?
> 
> This does what you want:
> 
> 	/* Reserve the space */
> 	int length = strlen("somethingselse1");

Whoops! Off-by-one error. :-(

This should be strlen("somethingelse1") + 1, since strlen doesn't count the
trailing '\0' of the string and you need to copy that as well.

> 	somename[0] = (char *) malloc(length);
> 	strncpy(somename[0], "somethingelse1", length);

Malcolm

-- 



More information about the Techtalk mailing list