473,320 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How to create separate character pointers?

I'd like to create separate character pointers,
pass them to a function to assign each one different value,
and assign the pointers to an array.

But when I try:

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

int main(void)
{
int i;

for (i = 0; i < 5; ++i)
{
char *str = "test";
printf("%p:%s\n", str, str);
}

return 0;
}

All the pointers refer to the same address.
When the 'char *str = "test"' is run, no new pointer is created?

Nov 8 '07 #1
14 1950
Lambda wrote:
I'd like to create separate character pointers,
pass them to a function to assign each one different value,
and assign the pointers to an array.

But when I try:

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

int main(void)
{
int i;

for (i = 0; i < 5; ++i)
{
char *str = "test";
printf("%p:%s\n", str, str);
}

return 0;
}

All the pointers refer to the same address.
When the 'char *str = "test"' is run, no new pointer is created?
Each execution of the loop creates a new `str' variable.
Each time, that variable is initialized to point to the same
"test" string. If your telephone number is written on five
pieces of paper, it doesn't mean you have five different
telephones.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Nov 8 '07 #2
Lambda wrote:
I'd like to create separate character pointers,
pass them to a function to assign each one different value,
and assign the pointers to an array.

But when I try:

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

int main(void)
{
int i;

for (i = 0; i < 5; ++i)
{
char *str = "test";
printf("%p:%s\n", str, str);
}

return 0;
}

All the pointers refer to the same address.
When the 'char *str = "test"' is run, no new pointer is created?
A new pointer object is created each time, though on many
implementations that new pointer object is likely to be created in
exactly the same location. The key problem isn't the pointer object,
it's the pointer value that it's initialized with. When you write a
string literal such as "test" in contexts like this one, what happens is
that an unnamed array of 5 characters is created and filled in with 't',
'e', 's', 't', and '\0'. The string literal is treated as a pointer to
that array. Therefore, every time you go through the loop, you
initialize your pointer object with a pointer value that points at the
same unnamed array.

The right way to fix this depends very much on what it is that you're
trying to do. The simplest approach that matches your description would
be as follows:

#include <stdio.h>
int main(void)
{
char str1[] = "test";
char str2[] = "test";
char str3[] = "test";
char str4[] = "test";
char str5[] = "test";
char *array[5] = {str1, str2, str3, str4, str5};
int i;

for(i=0; i<5; ++i)
printf("%p:%s\n", array[i], array[i]);
// Use array.

return 0;
}

Note that in this case the string literals are used to initialize an
array, not a pointer in an array. In this case, no unnamed array is
created; instead, each definition creates a separate array and
initializes that array

While the above code matches your description, I doubt that it's what
you really want. The following more complicated case is probably closer
to what you're looking for:

#include <stdio.h>
#include <stdlib.h>
#define STRINGS 5

int main(void)
{
char *array[STRINGS];
int i;
for(i=0; i<STRINGS; i++)
{
array[i] = malloc(5);
if(array[i])
{
strcpy(array[i], "test");
printf("%p:%s\n", array[i], array[i]);
}
else
{
printf("%p: failed allocation\n", array[i]);
}
}

for(i=0; i<STRINGS; i++)
free(array[i]);
return 0;
}
Nov 8 '07 #3
James Kuyper wrote:
>
.... snip ...
>
for(i=0; i<5; ++i)
printf("%p:%s\n", array[i], array[i]);
// Use array.
To avoid awkward line wraps, avoid using the // comments in posted
material. They are also illegal under C90.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 8 '07 #4
CBFalconer wrote:
James Kuyper wrote:
... snip ...
> for(i=0; i<5; ++i)
printf("%p:%s\n", array[i], array[i]);
// Use array.

To avoid awkward line wraps, avoid using the // comments in posted
material.
They are also illegal under C90.
I write for the current standard, not the old one. It's been many years
since I last worked on a system that didn't have a compiler which would
support at least that much of C99.
Nov 8 '07 #5
James Kuyper wrote:
CBFalconer wrote:
>James Kuyper wrote:
... snip ...
>> for(i=0; i<5; ++i)
printf("%p:%s\n", array[i], array[i]);
// Use array.

To avoid awkward line wraps, avoid using the // comments in posted
material.
>They are also illegal under C90.

I write for the current standard, not the old one. It's been many years
since I last worked on a system that didn't have a compiler which would
support at least that much of C99.
Fair enough, but Chuck's first point still applies. "/* ... */" works
fine when wrapped by a newsreader, while "//" doesn't

It's not a problem in the specific code you posted, but in general I'd
agree with Chuck that "/* ... */" is a better choice for newsgroup postings.
Nov 8 '07 #6
Eric wrote:
) <snip>
) for (i = 0; i < 5; ++i)
) {
) char *str = "test";
) printf("%p:%s\n", str, str);
) }
)
) Each execution of the loop creates a new `str' variable.
) Each time, that variable is initialized to point to the same
) "test" string. If your telephone number is written on five
) pieces of paper, it doesn't mean you have five different
) telephones.

I bet that even if you wrote printf("%p->%p:%s\n", &str, str, str);
that you can't find a compiler that wouldn't output the same each
iteration, although I'm sure the Standard would allow it.
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
Nov 8 '07 #7
On Nov 8, 6:43 am, CBFalconer <cbfalco...@yahoo.comwrote:
James Kuyper wrote:

... snip ...
for(i=0; i<5; ++i)
printf("%p:%s\n", array[i], array[i]);
// Use array.

To avoid awkward line wraps, avoid using the // comments in posted
material. They are also illegal under C90.
Nice example of why you got to have very thick skin to read this
group. You don't even need to cast return value of malloc!
>
--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account fromhttp://www.teranews.com
Just wonderful. Pure wisdom from Chuck.

--
Posted via groups.google.com. It's so much worse than teranews. Yeah!

Nov 8 '07 #8
Op Thu, 08 Nov 2007 09:50:54 -0800 schreef ym******@gmail.com:
On Nov 8, 6:43 am, CBFalconer <cbfalco...@yahoo.comwrote:
>James Kuyper wrote:

... snip ...
>> for(i=0; i<5; ++i)
printf("%p:%s\n", array[i], array[i]);
// Use array.

To avoid awkward line wraps, avoid using the // comments in posted
material. They are also illegal under C90.

Nice example of why you got to have very thick skin to read this
group. You don't even need to cast return value of malloc!
Of course not, C isn't C++
--
Coos
Nov 8 '07 #9
James Kuyper wrote:
CBFalconer wrote:
>James Kuyper wrote:
... snip ...
>> for(i=0; i<5; ++i)
printf("%p:%s\n", array[i], array[i]);
// Use array.

To avoid awkward line wraps, avoid using the // comments in posted
material.
>They are also illegal under C90.

I write for the current standard, not the old one. It's been many
years since I last worked on a system that didn't have a compiler
which would support at least that much of C99.
/* .. */ is valid under all systems, and is immune to usenet line
wrap.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 8 '07 #10
CBFalconer wrote:
James Kuyper wrote:
....
I write for the current standard, not the old one. It's been many
years since I last worked on a system that didn't have a compiler
which would support at least that much of C99.

/* .. */ is valid under all systems,
I restrict myself to the common subset of C90 and C99 only when
required to compile for C90 (which is true only in my work
environment). Otherwise, I write C99 code which takes full advantage
of every feature of C99 that I consider an improvement over C90.

Don't expect me to follow your coding standards, though I suppose
there's no way I can stop you from complaining when I violate them.
However, I would prefer it if you would refrain from doing so. How
would you feel if I complained every time you posted code that failed
to take advantage of C99 features that I consider to be improvements?
... and is immune to usenet line
wrap.
I try to avoid posting code examples with lines long enough to wrap.
If I've failed to achieve that goal, I consider the line length to be
the problem, not the use of // comments.

Nov 9 '07 #11
Willem wrote:
Eric wrote:
) <snip>
) for (i = 0; i < 5; ++i)
) {
) char *str = "test";
) printf("%p:%s\n", str, str);
) }
)
) Each execution of the loop creates a new `str' variable.
) Each time, that variable is initialized to point to the same
) "test" string. If your telephone number is written on five
) pieces of paper, it doesn't mean you have five different
) telephones.

I bet that even if you wrote printf("%p->%p:%s\n", &str, str, str);
that you can't find a compiler that wouldn't output the same each
iteration, although I'm sure the Standard would allow it.
The fact that two objects share the same memory location
at different times in the program's execution does not make
them the same object.

Example 1:

char *p, *q;
p = malloc(42); /* assume success */
strcpy (p, "Zaphod");
free (p);
q = malloc(21); /* assume success */
strcpy (q, "Beeblebrox");

Even if it turns out that p and q refer (during their respective
periods of validity) to the same address, they do not refer to
the same object.

Example 2:

int f1(void) {
int i = 42;
return i;
}

int f2(void) {
int j = 24;
return j;
}

int driver(void) {
return f1() + f2();
}

Even if it turns out that i and j share the same memory location
they are different objects.

Perhaps my example of the five pieces of paper would have
been better if I'd specified that each was burned before the
next was written.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Nov 9 '07 #12
ja*********@verizon.net wrote:
CBFalconer wrote:
>James Kuyper wrote:
...
>>I write for the current standard, not the old one. It's been many
years since I last worked on a system that didn't have a compiler
which would support at least that much of C99.

/* .. */ is valid under all systems,

I restrict myself to the common subset of C90 and C99 only when
required to compile for C90 (which is true only in my work
environment). Otherwise, I write C99 code which takes full advantage
of every feature of C99 that I consider an improvement over C90.

Don't expect me to follow your coding standards, though I suppose
there's no way I can stop you from complaining when I violate them.
It's not really a complaint, just intended to point out how you can
avoid nuisances in Usenet. Another point is that the receiver may
not have a compiler that accepts //. I happen to believe in
maximizing portability, barring nasty penalties.

No more need be said about it. Until I forget :-)

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 9 '07 #13
Lambda <st*********@gmail.comwrites:
I'd like to create separate character pointers,
pass them to a function to assign each one different value,
and assign the pointers to an array.

But when I try:

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

int main(void)
{
int i;

for (i = 0; i < 5; ++i)
{
char *str = "test";
printf("%p:%s\n", str, str);
}

return 0;
}

All the pointers refer to the same address.
When the 'char *str = "test"' is run, no new pointer is created?
You are printing the value of the pointer, which is the address of the
character literal "test". If the executable were ELF formatted, this
would most likely be an address in the .rodata section.

Chip

--
Charles M. "Chip" Coldwell
"Turn on, log in, tune out"
Somerville, Massachusetts, New England
Nov 9 '07 #14
On Nov 9, 11:17 am, jameskuy...@verizon.net wrote:
CBFalconer wrote:
....
... and is immune to usenet line wrap.

I try to avoid posting code examples with lines long enough to wrap.
To help with that, here is a little 'Text Width Check'
tool that I offer.
<http://www.physci.org/twc.jnlp>

I recommend keeping line width to less than 62 chars for
usenet posts.

--
Andrew T.
PhySci.org

Nov 11 '07 #15

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

Similar topics

15
by: tschi-p | last post by:
maybe my question is quite simple, but although searching like wild I cannot find a solution. I just want to append to a file, let's say to "c:\my folder\filename1.txt". Normally with...
43
by: Anitha | last post by:
Hi I observed something while coding the other day: if I declare a character array as char s, and try to use it as any other character array..it works perfectly fine most of the times. It...
3
by: linguae | last post by:
Hello. In my C program, I have an array of character pointers. I'm trying to input character strings to each index of the character pointer array using scanf(), but when I run the program, I get...
16
by: thenightfly | last post by:
Ok, I know all about how binary numbers translate into text characters. My question is what exactly IS a text character? Is it a bitmap?
18
by: james | last post by:
Hi, I am loading a CSV file ( Comma Seperated Value) into a Richtext box. I have a routine that splits the data up when it hits the "," and then copies the results into a listbox. The data also...
4
by: Jan | last post by:
Have an SQL create/import script. Running this on SQL would make it create a table with some values. Can Access2003 somehow use such and SQL script? I went into SQL query view to try it out, but...
4
by: sandeep | last post by:
When we use STL which memory space it will use whither it is stack or heap or data segment How to make STL to create in heap? How to make whole container to create in heap? I think container...
23
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these...
14
by: Shhnwz.a | last post by:
Hi, I am in confusion regarding jargons. When it is technically correct to say.. String or Character Array.in c. just give me your perspectives in this issue. Thanx in Advance.
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.