473,800 Members | 2,696 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1981
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...@yah oo.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.co m
Just wonderful. Pure wisdom from Chuck.

--
Posted via groups.google.c om. 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...@yah oo.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

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

Similar topics

15
46524
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 append-option, the file is created if it doesn't exist. But I want also the folder to be created if it does not exist - now if the specified folder is not available, the file isn't created at all. Is there an additional option at fopen that I couldn't...
43
2763
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 holds strings of any length. I guess what is happening here is that this array initially holds only '\0' and hence is of length 1. But sometimes, when I tried to write some functions and do some
3
14146
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 segmentation faults and core dumps. The problem occurs when the program calls scanf(). I don't know what is wrong with it. Here is my code: #include "stdio.h" #define SIZE 5
16
2701
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
4635
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 has some different characters in it that I am trying to remove. The small a with two dots over it and the small y with two dots over it. Here is my code so far to remove the small y: Private Sub Button2_Click(ByVal sender As System.Object, ByVal...
4
3341
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 the amount of data was too big to paste in according to Access. Sample data: -- -- PostgreSQL database dump
4
3696
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 uses stack is it correct ? I am using double linked list so in place of it I want to use STL for #include<stdio.h> #include<iostream>
23
7423
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 in an array. The application compiles but aborts without giving me any useful information. What I suspect is happening is infinite recursion. Each Directory object creates an array of Subdirectories each of which has an array of...
14
4095
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
9691
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...
1
10255
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
10036
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
9092
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...
1
7582
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6815
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();...
0
5473
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...
2
3765
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2948
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.