
question about array of pointers to chars
What you want is something like the following:
#include <stdio.h>
int main( void )
{
char *name[] = {"January", "February", "March", "April"};
int i;
for ( i = 0; i < sizeof name / sizeof name[ 0 ]; ++i )
puts( name[ i ] );
return 0;
Quote:
}
If you were to have the following statement:
char text[] = "Hello World";
then sizeof (text) would be 12. The array has 11 characters and the
terminating NUL character. In your example, we will assume a pointer is 4
bytes. "Name" is an array of pointers. In this particular case, it is an
array of 4 pointers that are 4-bytes each, i.e. 16 bytes. "Name[ 0 ]"
contains one pointer which (as I've stated) is 4 bytes. Therefore, sizeof
name / sizeof name[ 0 ] is the same as 16 / 4 which is 4. Some
reinterpretations of my loop are:
for ( i = 0; i < 16 / 4; ++i )
puts( name[ i ] );
and
for ( i = 0; i < 4; ++i )
puts( name[ i ] );
You probably don't have to worry much about what looks like constant
division because a decent optimizing compiler will automatically compute
"sizeof name / sizeof name[ 0 ]" to be 4 only once (again assuming the size
of your pointers are 4 bytes).
--
Increase the Peace!
Charles LaCour
Quote:
>Good afternoon everybody,
>I have a problem with printing the pointer array
>char *name[] = {"January", "February", "March", "April"};
>What I want to do is print the names "January", "February", "March" and
>"April"
>and I just can't get it done the way I want it. I have several solutions
>which are not very satisfactory or just plain wrong. For example, I have
>used
>this:
>while (name[0] <= name[3])
>{
> while (*name[0] != '\0')
> printf ("%c", *(name[0])++);
> printf ("\n");
> ++name[0];
>}
>which makes the false assumption that "January" is stored in memory before
>"February" etc (it works on quite a number of machines though). I also have
>appended a "1" to the array, so that I can use the code
>while (*(name[0]) != '1')
>{
> while (*(name[0]) != '\0')
> printf ("%c", *(name[0]++));
> printf ("\n");
> ++name[0];
>}
>which is extremely ugly. The problem looks a little like the argv and argc
>manipulation (page 117 of K&R, the page where I got stuck with this
>problem),
>but the advantage there is that a counter-controlled loop can be written,
>because we have an argc. Is there some way equal to that approach but
>without
>the use of a special counter that keeps track of the number of arguments?
>I'm not
>looking for a simple for-loop.
>Any help or pointers to get this annoying problem out of the way would be
>appreciated.
>Cordially,
>Casper van Eersel