473,715 Members | 6,096 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to change the the value which is pointed by a char pointer by a function?

Dear all,

I met a char pointer problem. please help,thanks.
How to change the the value which is pointed by a char pointer by a
function?

for example,
-----------------------------------------------------
#include <iostream>
using namespace std;

void addstr(char *str,int len) {
str=new char[len];
for (int i=0;i<(len-1);i++)
{
*(str+i)=char(6 5+2*i);
}
}

int main()
{
char *test;
int len=10;
addstr(test,len );
for (int i=0;*(test+i);i ++)
cout << "here=" << *(test+i);
cout << endl;
}
---------------------------------------------------
Why does *test still equal to NULL?
How do I fix the function addstr so that test=str?

Best Regards,
cylin.
Jul 19 '05 #1
3 3250

"> for example,
-----------------------------------------------------
#include <iostream>
using namespace std;

void addstr(char *str,int len) {
Change the above line to void addstr(char *& str,int len) {
str=new char[len];
for (int i=0;i<(len-1);i++)
{
*(str+i)=char(6 5+2*i);
}
}

int main()
{
char *test;
int len=10;
addstr(test,len );
for (int i=0;*(test+i);i ++)
cout << "here=" << *(test+i);
cout << endl;
}


It should work now.

--
With best wishes,
J.Schafer
Jul 19 '05 #2
"cylin" <cy***@avant.co m.tw> wrote in message
news:bf******** ****@ID-154203.news.uni-berlin.de...
Dear all,

I met a char pointer problem. please help,thanks.
How to change the the value which is pointed by a char pointer by a
function?

for example,
-----------------------------------------------------
#include <iostream>
using namespace std;

void addstr(char *str,int len) {
'str' is of type char*. Write it like this to make it more obvious:

void addstr(char* str,int len)
str=new char[len];
Here you are just changing the local variable 'str'. See below.
for (int i=0;i<(len-1);i++)
{
*(str+i)=char(6 5+2*i);
}
}

int main()
{
char *test;
int len=10;
addstr(test,len );
Above I said 'str' is of type 'char*'. 'test' is of type 'char*' as
well. So what happens here is, you create a /copy/ the value of 'test' (the
uninitialized pointer value (*)). This means that if 'addstr' modifies it,
it actually only modifies the copy and your 'test' variable is left
unchangd. That is why you do not want the function 'addstr' to have a copy
of the pointer, you want it to be able to modify the pointer itself, so you
either need to pass a pointer to the pointer, or a reference to the pointer.
for (int i=0;*(test+i);i ++)
cout << "here=" << *(test+i);
cout << endl;
}
---------------------------------------------------
Why does *test still equal to NULL?
'*test' is not NULL. '*test' is undefined, just like 'test' (the pointer
value itself) has an unknown value.
How do I fix the function addstr so that test=str?


Pass the pointer value by reference:

void addstr (char*& str, int len);
To someone with more knowledge of the Standard:

(*) Is the following legal?

char* ptr;
char* ptr2 = ptr;

? Because I remember a discussion (in comp.lang.c++.m oderated maybe?)
Where it was said that a pointer with an invalid value may not even be read.

regards
--
jb

(replace y with x if you want to reply by e-mail)
Jul 19 '05 #3
"cylin" <cy***@avant.co m.tw> wrote in message
news:bf******** ****@ID-154203.news.uni-berlin.de...
Dear all,

I met a char pointer problem. please help,thanks.
How to change the the value which is pointed by a char pointer by a
function?
Other people seemed to answer this question, but other parts of this code
were fishy, so I thought I'd add 2c.
for example,
-----------------------------------------------------
#include <iostream>
using namespace std;

void addstr(char * & str,int len) { // as others suggested
str=new char[len];
for (int i=0;i<(len-1);i++)
{
*(str+i)=char(6 5+2*i);
}
*(str + len - 1) = 0; // remember to terminate string!
}
Maybe I'm missing something, but you need to make sure to actually set the
last character to 0; if you don't, you could get 0xDEADBEEF.

int main()
{
char *test;
int len=10;
addstr(test,len );
for (int i=0;*(test+i);i ++)
cout << "here=" << *(test+i);
cout << endl;
}


Consider incrementing pointers instead of integers for this type of thing;
the convenience of doing so is one reason zero-terminated strings were
popular for so long.

char *c = test;
while (*c)
cout << "here=" << *c++;

Better yet, use std::string if at all possible; it's cleaner and safer.
Jul 19 '05 #4

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

Similar topics

4
1962
by: gsyoon | last post by:
hi, all. I'm trying to make a "framework" to store the return value of a function to a global memory. My first attempt was 1) void store_to_global( char * type_name ) { if ( strcmp( type_name, "CLASS_A") )
2
13242
by: Sara Shoemaker | last post by:
Hi all - I am trying to launch a web browser from within my code for Linux. The problem is that I am getting no failure code back when the browser doesn't launch. (I'm trying to force a failure case so I can test the alert dialog, so I am trying to launch a browser that I know doesn't exist on my machine). I am checking the return value from the call to system(), and am checking the WEXITSTATUS() of the return code, and both evaluate...
3
8477
by: Don Pasquale | last post by:
The following function intends to delete "numberoflines" lines from a text file, named "s" (string pointer) and pointed to by file pointer "fp", starting from line "line". Now, the function works an inteded, but I think that this is purely coincidential. I'm using a temp file to copy the contents of the text file, and then, copy the last lines that i want to keep, on top of those i want to delete.I fwrite an EOF character after the...
4
1784
by: jrefactors | last post by:
In the following program, are parameters s in function reverse() and x in function count() both pass by value? How come value k is not changed, but value str has changed? Please advise. thanks!! ============================================ void reverse(char s); void count(int x);
1
2287
by: Hemant Mohan | last post by:
Consider the following program snipet: <snip> typedef struct { unsigned char a ; unsigned char b ; unsigned char c ;
4
2761
by: arnuld | last post by:
1.) we usually say /return 0/ indicates success e.g #include <iostream> int main() { int i=3; std::cout << i << std::endl; return 0;
12
2079
by: Frodo Baggins | last post by:
Hi I need to know the size of the memory block pointed to by a char* in a function receiving this pointer. Typically, this pointer points to a string. strlen() will not do the job since sometimes the string is not null terminated. That is: int foo(void) {
45
18882
by: Zytan | last post by:
This returns the following error: "Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this' because it is not a variable" and I have no idea why! Do lists return copies of their elements? Why can't I change the element itself? class Program { private struct MyStruct
10
1843
by: somenath | last post by:
Hi All, I was trying to understand the pass by value mechanism in c. To understand it I wrote a Small code as mentioned bellow. #include<stdio.h> #include<stdlib.h> #include<string.h> void check(char *src);
0
8823
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
9343
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
9198
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
9104
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
9047
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...
1
6646
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
4738
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3175
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
2
2541
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.