[Techtalk] C Programming Question
Julie
jockgrrl at austin.rr.com
Thu Jun 13 21:25:08 EST 2002
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");
> somename[0] = (char *) malloc(length);
> strncpy(somename[0], "somethingelse1", length);
>
> Note that if the initial value ("data1") was not allocated as above, you
> may need to free its memory (however, in the above case, this is not
> required).
That's pretty barfy code. Try something like
somename[0] = strdup ("somethingelse1");
It completely avoids the off-by-one error that you (and a lot of
other programmers) made. If you really, really want to know the
length of "somethingelse1", and "somethingelse1" is a fixed string,
consider
int length = sizeof "somethingelse1";
somename[0] = strcpy (malloc (length), "somethingelse1");
If you're curious about the use of "sizeof" above, try this
program --
main ()
{
int length = sizeof "five";
printf ("length = %d\n", length);
}
The advantage of using "sizeof" instead of strlen() is you
can do static allocations using sizeof, but not with strlen().
So you can do clever things like
char *temp_file_name = "/tmp/proggyXXXXXXXX";
char *temp_file_pid = temp_file_name + sizeof "/tmp/proggy";
...
sprintf (temp_file_pid, "%08.8d", getpid ());
...
and avoid run-time dorking with addresses and what-not. Or
perhaps even more bizarre
char temp_file_name[sizeof "/tmp/proggy" + 3 * sizeof (pid_t) + 1];
...
sprintf (temp_file_name, "/tmp/proggy%d", getpid ());
...
Handy for writing code on machines with PIDs that are 16, 32
or 64 bits long.
--
Julianne Frances Haugh Life is either a daring adventure
jockgrrl at austin.rr.com or nothing at all.
-- Helen Keller
More information about the Techtalk
mailing list