473,779 Members | 2,015 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

walking through an array of char pointers

I can't seem to get this to work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *names[3];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0') {
printf("%s\n",* np);
np++;
}

return 0;
}

after printing the 3 names, it prints garbage then sometimes seg faults.
I know i can do it easily using a for loop, but that's not what I am looking
for. I was under the impression names is actually:

[] --> "jack\0"
[] --> "jill\0"
[] --> "zack\0"
[] --> \0
If, that is so, shouldn't I be able to perform the above loop?

This works:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *names[3];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0')
printf("\%s\n", *(*np)++);
np++;
while (**np != '\0')
printf("\%s\n", *(*np)++);
np++;
while (**np != '\0')
printf("\%s\n", *(*np)++);

return 0;
{

But, I need 3 loops for what I'd like to do in one.
I do not want to use the fact that I know there are n
strings in the array. I want to use the fact that each string is
null terminated then there is a final null terminator.

any suggestions would be appreciated.

- gaga
Nov 14 '05 #1
19 14521
gaga <zi*******@aol. com> wrote:
I can't seem to get this to work: #include <stdio.h>
#include <stdlib.h>
#include <string.h> int main()
{
char *names[3];
char **np; names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0') {
np hasn't been in initialized at this point. I guess you meant to
set
np = names;

before the start of the loop. But even then there's no reason why
the loop should stop after printing "zack" because afterwards np
would get incremented to point _after_ the third array element,
which probably is some random bit pattern which, when interpreted
as a char pointer, doesn't point to something where a '\0' charac-
ter would be stored. So you would need a fourth element of your
'names' array that would point to an empty string.
printf("%s\n",* np);
np++;
}

return 0;
}
You would need something like this instead to get it working:

int main( void )
{
char *names[ ] = { "jack", "jill", "zack", "" };
char **np = names;

while ( **np != '\0' )
printf( "%s\n", *np++ );
return EXIT_SUCCESS;
}
This works: #include <stdio.h>
#include <stdlib.h>
#include <string.h> int main()
{
char *names[3];
char **np; names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0')
printf("\%s\n", *(*np)++);
np++;
while (**np != '\0')
printf("\%s\n", *(*np)++);
np++;
while (**np != '\0')
printf("\%s\n", *(*np)++);

return 0;
{


If this version works for you it's just by accident - on my machine it
crashes immediately. And what's "\%s" and "*(*np)++" supposed to do?

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #2
gaga wrote:

I can't seem to get this to work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *names[3]; 4 /* need a final pointer */ char **np;
np = &names; /* initialize */ names[0] = "jack";
names[1] = "jill";
names[2] = "zack"; names[3] = ""; /* end marker */
while (**np != '\0') {
printf("%s\n",* np);
np++;
}

return 0;
}

after printing the 3 names, it prints garbage then sometimes seg
faults. I know i can do it easily using a for loop, but that's
not what I am looking for. I was under the impression names is


Try the commented changes/additions above. Simpler is:

char *names[] = {"jack", "jill", "zack", ""};
char* *np;

for (np = &names; **np; np++) printf("%s\n, *np);
--
fix (vb.): 1. to paper over, obscure, hide from public view; 2.
to work around, in a way that produces unintended consequences
that are worse than the original problem. Usage: "Windows ME
fixes many of the shortcomings of Windows 98 SE". - Hutchison

Nov 14 '05 #3
CBFalconer wrote:
gaga wrote:
I can't seem to get this to work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *names[3];


4 /* need a final pointer */
char **np;


np = &names; /* initialize */
names[0] = "jack";
names[1] = "jill";
names[2] = "zack";


names[3] = ""; /* end marker */
while (**np != '\0') {
printf("%s\n",* np);
np++;
}

return 0;
}

after printing the 3 names, it prints garbage then sometimes seg
faults. I know i can do it easily using a for loop, but that's
not what I am looking for. I was under the impression names is

Try the commented changes/additions above. Simpler is:

char *names[] = {"jack", "jill", "zack", ""};
char* *np;

for (np = &names; **np; np++) printf("%s\n, *np);


char *names[] = {"jack", "jill", "zack", NULL };
char **np = names;
while (*np) printf("%s\n", *np++);

Note that names is an array of pointers to char. 'names' decays to a
pointer to the array's first element. A pointer to char. So the
assignment is 'np = names;', not 'np = &names;'.

--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #4
gaga wrote:
I can't seem to get this to work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *names[3];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0') {
printf("%s\n",* np);
np++;
}

return 0;
}

after printing the 3 names, it prints garbage then sometimes seg faults.
I know i can do it easily using a for loop, but that's not what I am looking
for. I was under the impression names is actually:

[] --> "jack\0"
[] --> "jill\0"
[] --> "zack\0"
[] --> \0


That would be true if you had declared an array of four pointers to char
(count your list) and set the last one to point to an empty string. You
obviously did not do that.
char *names[] = {"Jack", "Jill", "Zack", ""};

Nov 14 '05 #5
zi*******@aol.c om (gaga) wrote in message news:<56******* *************** ****@posting.go ogle.com>...
I can't seem to get this to work:

#include <stdio.h> #include <stdlib.h>
#include <string.h>
You don't need those last two.

int main()
{
char *names[3];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0') {
Here is your first problem. You are dereferencing a pointer (np)
which you haven't assigned to yet. I'm not sure what you are trying
to do here.
printf("%s\n",* np);
Don't know how this could possibly work...
np++;
}

return 0;
}

after printing the 3 names, it prints garbage then sometimes seg faults.
That's because you are trying to access memory pointed to by a pointer
that hasn't been initialized with a valid location.
I know i can do it easily using a for loop, but that's not what I am looking
for. I was under the impression names is actually:

[] --> "jack\0"
[] --> "jill\0"
[] --> "zack\0"
Good so far...
[] --> \0
Nope. "char *names[3];" declares an array of 3 pointers to char,
that's it. You may be getting confused with the '\0' that is
automatically added to string literals.

There are a few ways to do what you want to do. You can keep track of
how many elements are in the array and use a for loop to iterate over
them or you can do something like the following which uses a NULL
pointer as the last element in the array and is in the spirit of what
I think you were trying to do:

#include <stdio.h>

int main(void)
{
char *names[4];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";
names[3] = NULL;

np = names;

while (*np) {
printf("%s\n",* np);
np++;
}

return 0;
}

If, that is so, shouldn't I be able to perform the above loop?

This works:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *names[3];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0')
printf("\%s\n", *(*np)++);
np++;
while (**np != '\0')
printf("\%s\n", *(*np)++);
np++;
while (**np != '\0')
printf("\%s\n", *(*np)++);

return 0;
{


There are more problems with this code than I care to comment on, get
rid of it.

Rob Gamble
Nov 14 '05 #6
gaga wrote:

I can't seem to get this to work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *names[3];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0') {
printf("%s\n",* np);
np++;
}

return 0;
}

#include <stdio.h>

int main(void)
{
char *names[] = {"jack", "jill", "zack", NULL};
char **np;

for (np = names; *np != NULL; ++np) {
puts(*np);
}
return 0;
}

--
pete
Nov 14 '05 #7
pete wrote:
gaga wrote:
I can't seem to get this to work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *names[3];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0') {
printf("%s\n",* np);
np++;
}

return 0;
}


#include <stdio.h>

int main(void)
{
char *names[] = {"jack", "jill", "zack", NULL};
char **np;

for (np = names; *np != NULL; ++np) {
puts(*np);
}
return 0;
}


Ok, printf is too complicated but for is too.

#include <stdio.h>

int main(void) {
char *names[] = {"jack", "jill", "zack", NULL};
char **np = names;
while (*np) puts(*np++);
return 0;
}

--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #8
ro**********@ho tmail.com (tigervamp) wrote in message news:<c9******* *************** ****@posting.go ogle.com>...
zi*******@aol.c om (gaga) wrote in message news:<56******* *************** ****@posting.go ogle.com>...
I can't seem to get this to work:

#include <stdio.h>

#include <stdlib.h>
#include <string.h>


You don't need those last two.

int main()
{
char *names[3];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0') {


Here is your first problem. You are dereferencing a pointer (np)
which you haven't assigned to yet. I'm not sure what you are trying
to do here.
printf("%s\n",* np);


Don't know how this could possibly work...
np++;
}

return 0;
}

after printing the 3 names, it prints garbage then sometimes seg faults.


That's because you are trying to access memory pointed to by a pointer
that hasn't been initialized with a valid location.
I know i can do it easily using a for loop, but that's not what I am looking
for. I was under the impression names is actually:

[] --> "jack\0"
[] --> "jill\0"
[] --> "zack\0"


Good so far...
[] --> \0


Nope. "char *names[3];" declares an array of 3 pointers to char,
that's it. You may be getting confused with the '\0' that is
automatically added to string literals.

There are a few ways to do what you want to do. You can keep track of
how many elements are in the array and use a for loop to iterate over
them or you can do something like the following which uses a NULL
pointer as the last element in the array and is in the spirit of what
I think you were trying to do:

#include <stdio.h>

int main(void)
{
char *names[4];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";
names[3] = NULL;

np = names;

while (*np) {
printf("%s\n",* np);
np++;
}

return 0;
}

If, that is so, shouldn't I be able to perform the above loop?

This works:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *names[3];
char **np;

names[0] = "jack";
names[1] = "jill";
names[2] = "zack";

while (**np != '\0')
printf("\%s\n", *(*np)++);
np++;
while (**np != '\0')
printf("\%s\n", *(*np)++);
np++;
while (**np != '\0')
printf("\%s\n", *(*np)++);

return 0;
{


There are more problems with this code than I care to comment on, get
rid of it.

Rob Gamble

Guys and gals....

you suggestions have been helpful, much appreciated, and correct.
But my blunder caused me to not get my point across.
I did not initialize **np, yes, but that was a copy paste mistake.

So, I guess where I'm really troubled is here:

All the solutions were right, but i'm gonna use Joe's here:

char *names[] = {"jack", "jill", "zack", NULL };
char **np = names;
while (*np) printf("%s\n", *np++);
Ok, that works, but, why is the last NULL needed in names?
Shouldn't that be done already? Why does this fail?

char *names[] = {"jack", "jill", "zack"};
char **np = names;
while (*np) printf("%s\n", *np++);
I guess that's what I'm driving at, sorry for the fck up earlier.

Please correct me if i am wrong, isn't this:

char c[] = "yes"

really:

"yes\0"
If that is true, shouldn't this:

char *names[] = {"jack", "jill", "zack"};

really be this:

"jack\0", "jill\0", "zack\0", \0

why isn't a final null terminator appened after an array of pointers?

Is it a case of, "that's just how it is"?

a final clarification would be most appreciated.

thanks again,
gaga
Nov 14 '05 #9
Joe Wright wrote:
.... snip ...
char *names[] = {"jack", "jill", "zack", NULL };
char **np = names;
while (*np) printf("%s\n", *np++);

Note that names is an array of pointers to char. 'names' decays
to a pointer to the array's first element. A pointer to char. So
the assignment is 'np = names;', not 'np = &names;'.


I don't think so. names is locally declared, so the type being
used in the assignment is not subject to decay to a pointer. We
want a pointer to a char*, which is not the type of 'names',
because it is still an array. The value of "sizeof names" should
point this out. That is one reason I separate the *s in the
declaration:

char* *np = &names;

--
fix (vb.): 1. to paper over, obscure, hide from public view; 2.
to work around, in a way that produces unintended consequences
that are worse than the original problem. Usage: "Windows ME
fixes many of the shortcomings of Windows 98 SE". - Hutchison
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
4615
by: Gerald | last post by:
I have a problem with an array of pointers. In a program I'm writing, I have to read a file, containing thousands of short lines. The content of another file will be compared against each line later on. Before that happens there has been a problem that causes a crash of the program. This is a little program "test.exe" I wrote to test what happens. compiler: mingw 3.1.01 for win32 command line
2
7197
by: Steve | last post by:
I want an initializer for an array of pointers to arrays of strings. So I can do something like this: const char *t1 = { "a", "b", "c", NULL }; const char *t2 = { "p", "q", NULL }; const char *t3 = { "w", "x", "y", "z", NULL }; const char **test = { t1, t2, t3, NULL }; I was wondering whether the is a more elegant way of writing such an
8
3687
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was static; if the input file contained more than entries, tough. This time I want to do it right - use a dynamic array that increases in size with each word read from the file. A few test programs that make use of **List and realloc( List, blah...
7
2487
by: Frank M. | last post by:
I'm trying to declare an array of pointers to structures so that I can make the last element a NULL pointer. I figure that it would more easily allow my library routines to know when to stop processing the array. typedef struct screen_disp { int sd_row; int sd_col; char *sd_buff; } SCR_DISP;
8
17721
by: ptek | last post by:
Hi all, I'm quite new to pointers, so this might be a silly question :S I need to allocate an array of pointers to unsigned char type... So, if I needed instead to allocate an array of unsigned chars, i'll do this :
6
4420
by: Piotrek | last post by:
Hi there again! Last time you helped me with pointers - it let me to save many hours of searching for some solutions. And once again I have question. Let's declare array of pointers: char *O={"", "one", "two",..., "eighteen"}; char *T={"", "ten", "twenty",..., "eighty"}; And now I want to declare an array of arrays of pointers: something like:
15
636
by: Jess | last post by:
Hi, If I have an array of pointer like: char* a = {"a","b","c"}; then it works fine. Since "a" is effectively "a" char**, I tried the following, which doesn't work: char** a = {"a","b","c"};
5
16700
by: ramu | last post by:
Hi, Could anyone please tell me how to dereference a pointer to an array of pointers? Regards
9
1983
by: Slain | last post by:
I have more of a conceptual question now. Let us say I do this:- char *str; --create an array of pointers str= "John"; I thought this would automatically put John at some memory space and point str to it. My colleague argues that in flat bed memory this should not be done. A new should be used to allocate the memory and then point to it. Of course he didnt do the best job explaining, hence my question to you
0
9636
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10306
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10074
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9930
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8961
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5503
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.