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
19 14523
gaga <zi*******@aol. com> wrote: Please correct me if i am wrong, isn't this:
char c[] = "yes"
really:
"yes\0"
That creates an array of chars named 'c' and initialized with
the literal string "yes", i.e it's equivalent to writing
char c[] = { 'y', 'e', 's', '\0' };
If that is true, shouldn't this:
char *names[] = {"jack", "jill", "zack"};
really be this:
"jack\0", "jill\0", "zack\0", \0
No. A literal string like "zack" automatically has a '\0' at
the end. But the 'names' array is an array of char pointers.
So it just consists of 3 char pointers, each initialized to
point to a literal string.
why isn't a final null terminator appened after an array of pointers?
What would a "null terminator" for an array of char pointers be?
A pointer to an empty string? A NULL pointer?
Arrays are never automatically "null teminated". The only case
where you get an automatic "null terminator" is when you use
a literal string, i.e. something that's enclosed in double
quotes. Then the compiler automatically appends a '\0' character
to the characters you write between the quotes. But a literal
string isn't an array, you just can use it to e.g. initialize
an array of chars.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
CBFalconer <cb********@yah oo.com> wrote: 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
Locally or not, with
char **np = names;
'names' is used in value context and thus decays to a pointer. It's
equivalent to
char **np = &names[ 0 ];
which is just what's needed. On the other hand
char **np = &names;
gives you a compiler warning about assignment from incompatible
pointer type because you try to assign a pointer to an array of
pointers to a pointer to pointer.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de Je***********@p hysik.fu-berlin.de wrote: CBFalconer <cb********@yah oo.com> wrote: 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
Locally or not, with
char **np = names;
'names' is used in value context and thus decays to a pointer. It's equivalent to
char **np = &names[ 0 ];
which is just what's needed. On the other hand
char **np = &names;
gives you a compiler warning about assignment from incompatible pointer type because you try to assign a pointer to an array of pointers to a pointer to pointer.
I guess I am guilty of fuzzy thinking. Mmm - when was the last
time I made a mistake in public ...
--
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 Je***********@p hysik.fu-berlin.de wrote in message news:<2o******* *****@uni-berlin.de>... gaga <zi*******@aol. com> wrote: Please correct me if i am wrong, isn't this:
char c[] = "yes"
really:
"yes\0"
That creates an array of chars named 'c' and initialized with the literal string "yes", i.e it's equivalent to writing
char c[] = { 'y', 'e', 's', '\0' };
If that is true, shouldn't this:
char *names[] = {"jack", "jill", "zack"};
really be this:
"jack\0", "jill\0", "zack\0", \0
No. A literal string like "zack" automatically has a '\0' at the end. But the 'names' array is an array of char pointers. So it just consists of 3 char pointers, each initialized to point to a literal string.
why isn't a final null terminator appened after an array of pointers?
What would a "null terminator" for an array of char pointers be? A pointer to an empty string? A NULL pointer?
Arrays are never automatically "null teminated". The only case where you get an automatic "null terminator" is when you use a literal string, i.e. something that's enclosed in double quotes. Then the compiler automatically appends a '\0' character to the characters you write between the quotes. But a literal string isn't an array, you just can use it to e.g. initialize an array of chars. Regards, Jens
Jens,
Thanks for your suggestions and perspective. Your responses
will allow me to properly (finally) explain my source of confusion.
K&R(ansi) pages 114 and 115.
on 114 an array of char pointers is depicted as such:
[ * ]-----> illegal month\0
[ * ]-----> jan\0
[ * ]-----> feb\0
[ * ]-----> mar\0
which would confirm your remark,
"But the 'names' array is an array of char pointers. So it just consists of 3
char pointers, each initialized to point to a literal string."
and yet, on the very next page, when discussing the main() params, argc
and argv, argv which is an array of char pointers (or pointer to pointers),
it is depicted as such:
argv:
[ * ]-----> [ * ]-----> echo\0
[ * ]-----> hello\0
[ * ]-----> world\0
[ 0 ]
Interesting, 0, (or NULL), is appended for us onto the argv array of pointers,
but not to a locally declared array of pointers.
allow me to restate my original question...
why does this work?
int main(int argc, char *argv[])
{
while (*argv)
printf("\%s\n", *argv++);
return 0;
}
But this doesn't:
int main()
{
char *names[] = {"jack", "jill", "zack"};
while (*names)
printf("%s\n",* names++);
return 0;
}
Why is a NULL appended to argv, but not to locally declared
array of char pointers?
- gaga
gaga <zi*******@aol. com> wrote: K&R(ansi) pages 114 and 115.
on 114 an array of char pointers is depicted as such:
[ * ]-----> illegal month\0 [ * ]-----> jan\0 [ * ]-----> feb\0 [ * ]-----> mar\0
which would confirm your remark, "But the 'names' array is an array of char pointers. So it just consists of 3 char pointers, each initialized to point to a literal string."
and yet, on the very next page, when discussing the main() params, argc and argv, argv which is an array of char pointers (or pointer to pointers), it is depicted as such:
argv: [ * ]-----> [ * ]-----> echo\0 [ * ]-----> hello\0 [ * ]-----> world\0 [ 0 ]
Interesting, 0, (or NULL), is appended for us onto the argv array of pointers, but not to a locally declared array of pointers.
Yes, but the extra NULL pointer isn't there because argv is an array
of pointers or because it's coming from somewhere else but because,
according to the requirements, argv must be set up that way (i.e. to
have a NULL pointer as the last argument). Under some operating
systems you can execute a new program from within your own and in
that case you have to assemble argv for the new program yourself.
And thus you have to create an array of pointers with one more
element than you want to pass to the new program and have to
explicitely set that extra pointer to NULL in order to make that
array an array that can be used as the argv array. No magic involved
and nothing of that sort (i.e. appending an extra NULL pointer) gets
done for you automatically. That's exactly the same thing you must
do with your 'names' array.
allow me to restate my original question...
why does this work?
int main(int argc, char *argv[]) { while (*argv) printf("\%s\n", *argv++);
Because you're guaranteed that argv always has an extra element
that's set to NULL. It has been set up that way by whatever
invokes your program.
return 0; }
But this doesn't:
int main() { char *names[] = {"jack", "jill", "zack"}; while (*names) printf("%s\n",* names++); return 0; }
Because your 'names' array isn't argv and hasn't been set up like
argv would. To do that you have to add the extra NULL pointer at
the end.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Joe Wright wrote: pete wrote:
for (np = names; *np != NULL; ++np) { puts(*np); }
Ok, printf is too complicated but for is too.
char **np = names; while (*np) puts(*np++);
As points of style,
I prefer to compare pointers against NULL explicitly,
I always use compound statements with loops, ifs and elses,
and I prefer not to have side effects in function arguments.
--
pete Je***********@p hysik.fu-berlin.de wrote in message news:<2o******* *****@uni-berlin.de>... gaga <zi*******@aol. com> wrote: K&R(ansi) pages 114 and 115.
on 114 an array of char pointers is depicted as such:
[ * ]-----> illegal month\0 [ * ]-----> jan\0 [ * ]-----> feb\0 [ * ]-----> mar\0
which would confirm your remark, "But the 'names' array is an array of char pointers. So it just consists of 3 char pointers, each initialized to point to a literal string."
and yet, on the very next page, when discussing the main() params, argc and argv, argv which is an array of char pointers (or pointer to pointers), it is depicted as such:
argv: [ * ]-----> [ * ]-----> echo\0 [ * ]-----> hello\0 [ * ]-----> world\0 [ 0 ]
Interesting, 0, (or NULL), is appended for us onto the argv array of pointers, but not to a locally declared array of pointers.
Yes, but the extra NULL pointer isn't there because argv is an array of pointers or because it's coming from somewhere else but because, according to the requirements, argv must be set up that way (i.e. to have a NULL pointer as the last argument). Under some operating systems you can execute a new program from within your own and in that case you have to assemble argv for the new program yourself. And thus you have to create an array of pointers with one more element than you want to pass to the new program and have to explicitely set that extra pointer to NULL in order to make that array an array that can be used as the argv array. No magic involved and nothing of that sort (i.e. appending an extra NULL pointer) gets done for you automatically. That's exactly the same thing you must do with your 'names' array.
allow me to restate my original question...
why does this work?
int main(int argc, char *argv[]) { while (*argv) printf("\%s\n", *argv++);
Because you're guaranteed that argv always has an extra element that's set to NULL. It has been set up that way by whatever invokes your program.
return 0; }
But this doesn't:
int main() { char *names[] = {"jack", "jill", "zack"}; while (*names) printf("%s\n",* names++); return 0; }
Because your 'names' array isn't argv and hasn't been set up like argv would. To do that you have to add the extra NULL pointer at the end. Regards, Jens
Jens,
Thank you. Now I get.
Thanks for your patience and explanations.
Thanks to everyone else who contributed as well. Much appreciated.
- gaga zi*******@aol.c om (gaga) wrote: I can't seem to get this to work:
char *names[3];
names[0] = "jack"; names[1] = "jill"; names[2] = "zack";
I was under the impression names is actually:
[] --> "jack\0" [] --> "jill\0" [] --> "zack\0" [] --> \0
Explain how you think 4 values can fit into 3 memory locations?
pete wrote: Joe Wright wrote:
pete wrote:
for (np = names; *np != NULL; ++np) { puts(*np); }
Ok, printf is too complicated but for is too.
char **np = names; while (*np) puts(*np++);
As points of style, I prefer to compare pointers against NULL explicitly, I always use compound statements with loops, ifs and elses, and I prefer not to have side effects in function arguments.
A chacun son gout.
I seriously prefer 'if (p)' over 'if (p != NULL)'.
By 'compound statememts' I suppose you mean curly braces. The use of
curly braces to encompass one statement annoys me.
Expressing 'foo(a++)' is well defined. That a is incremented is not
a side effect. It is an explicit part of the language.
I hope this disagreement doesn't mean we can't play anymore. :=)
--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Joe Wright wrote: pete wrote:
I prefer not to have side effects in function arguments.
Expressing 'foo(a++)' is well defined. That a is incremented is not a side effect. It is an explicit part of the language.
"side effect" is technical term in C.
N869
5.1.2.3 Program execution
[#2] Accessing a volatile object, modifying an object,
modifying a file, or calling a function that does any of
those operations are all side effects, which are changes
in the state of the execution environment. Evaluation of an
expression may produce side effects.
--
pete This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
|
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
|
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...
|
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;
|
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 :
| |
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:
|
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"};
|
by: ramu |
last post by:
Hi,
Could anyone please tell me how to dereference a pointer to an
array of pointers?
Regards
|
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
|
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,...
|
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...
| |
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...
|
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,...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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
| |