HI, I am a little confused about char * and char[].
How would I be able to return a char* created in a function? Is new() the only way? How would I be able to return a
point and a value at the same time? I thought of a possible solution. However, I am not quite sure if I understood
char[] vs. char*. Any insight is greatly appreciated.
Here is the question:
----------------------
....
char * test() {
char[] buf = "abcdef";
return (char *)buf;
}
int main() {
char * p ;
p = test(); // I know that this call is useless. So I tried to modify the test() function to return the
// char * properly. I listed my solution down below. Please feel free to advise.
return 0;
}
----------------------
char * test (char * p) {
p = new char[20];
p = "abcdef";
return p;
}
int main() {
char * p;
char * value;
value = test(p);
cout << value << "\n";
}
This solution returns "abcdef" as the return value. However, p does not pertain the same address that was allocated in
test(). My question is:
1. Is this solution going to cause memory leak because I did not call "delete" to delete the memory allocated?
2. Why was not p's value pertained?
3. How should I change so that I can return a value as well as a char *?
Thanks.
Yang 7 3541
"Yang Song" <so******@blue. seas.upenn.edu> wrote in message
news:bj******** ***@netnews.upe nn.edu... HI, I am a little confused about char * and char[].
How would I be able to return a char* created in a function? Is new() the
only way? How would I be able to return a point and a value at the same time? I thought of a possible solution.
However, I am not quite sure if I understood char[] vs. char*. Any insight is greatly appreciated.
Here is the question: ---------------------- ...
char * test() { char[] buf = "abcdef"; return (char *)buf; }
int main() { char * p ; p = test(); // I know that this call is useless. So I tried to modify the
test() function to return the // char * properly. I listed my solution down below. Please feel free
to advise. return 0; }
----------------------
char * test (char * p) { p = new char[20]; p = "abcdef"; return p; }
int main() { char * p; char * value; value = test(p); cout << value << "\n"; }
This solution returns "abcdef" as the return value. However, p does not
pertain the same address that was allocated in test(). My question is:
1. Is this solution going to cause memory leak because I did not call
"delete" to delete the memory allocated?
Yes.
2. Why was not p's value pertained?
Pertained ..did you mean changed??
p = new char[20]; // makes p contain a valid heap address.
p = "abcdef"; //changes p point to a string literal now.
Haven't you changed what p contained ?
3. How should I change so that I can return a value as well as a char *?
Don't know for sure what you are trying still...
#include <iostream>
using namespace std;
char * test (char * p) {
p = new char[20]; // Not a very good idea..vulnerabl e to buffer overrun.
strcpy ( p, "abcdef");
return p;
}
int main() {
char * p = NULL;
char * value = NULL;
value = test(p);
cout << value << "\n";
delete p;
}
HTH,
J.Schafer #include <iostream> using namespace std;
char * test (char * p) { p = new char[20]; // Not a very good idea..vulnerabl e to buffer
overrun. strcpy ( p, "abcdef"); return p; }
int main() { char * p = NULL; char * value = NULL; value = test(p); cout << value << "\n";
delete p;
Above stmt should be -
delete value;
Even delete p; won't crash your program because it's valid to delete a null
pointer as is in this case.
But then it's a memory leak ;-).
Yang Song <so******@blue. seas.upenn.edu> wrote: HI, I am a little confused about char * and char[].
How would I be able to return a char* created in a function? Is new() the only way? How would I be able to return a point and a value at the same time? I thought of a possible solution. However, I am not quite sure if I understood char[] vs. char*. Any insight is greatly appreciated.
Here is the question: ---------------------- ...
char * test() { char[] buf = "abcdef"; return (char *)buf; }
int main() { char * p ; p = test(); // I know that this call is useless. So I tried to modify the test() function to return the // char * properly. I listed my solution down below. Please feel free to advise. return 0; }
----------------------
char * test (char * p) { p = new char[20]; p = "abcdef"; return p; }
int main() { char * p; char * value; value = test(p); cout << value << "\n"; }
This solution returns "abcdef" as the return value. However, p does not pertain the same address that was allocated in test(). My question is:
1. Is this solution going to cause memory leak because I did not call "delete" to delete the memory allocated? 2. Why was not p's value pertained? 3. How should I change so that I can return a value as well as a char *?
Thanks.
Yang
--
Kristofer Pettijohn kr*******@cyber netik.net
"Yang Song" <so******@blue. seas.upenn.edu> wrote in message
news:bj******** ***@netnews.upe nn.edu... HI, I am a little confused about char * and char[].
How would I be able to return a char* created in a function? Is new() the
only way? How would I be able to return a point and a value at the same time? I thought of a possible solution.
However, I am not quite sure if I understood char[] vs. char*. Any insight is greatly appreciated.
Here is the question: ---------------------- ...
char * test() { char[] buf = "abcdef"; return (char *)buf; }
This is incorrect. buf is an array which exists only in the function test.
You are returing a pointer to something which no longer exists.
This is OK because now you are returning a pointer to a string literal, and
string literal exists for the whole of the program.
char * test() {
char* buf = "abcdef";
return buf;
} int main() { char * p ; p = test(); // I know that this call is useless. So I tried to modify the
test() function to return the // char * properly. I listed my solution down below. Please feel free
to advise. return 0; }
----------------------
char * test (char * p) { p = new char[20]; p = "abcdef";
strcpy(p, "abcdef");
Your code makes p point at the string, you want to copy the string to your
allocated memory. strcpy does that.
return p; }
int main() { char * p; char * value; value = test(p); cout << value << "\n"; }
This solution returns "abcdef" as the return value. However, p does not
pertain the same address that was allocated in test(). My question is:
1. Is this solution going to cause memory leak because I did not call
"delete" to delete the memory allocated?
Yes
2. Why was not p's value pertained?
Because you changed it.
3. How should I change so that I can return a value as well as a char *?
Like this?
struct MyData
{
int my_value;
char* my_string;
};
MyData test()
{
MyData d;
d.my_string = new char[20];
strcpy(d.my_str ing, "abcdef");
d.my_value = 123;
return d;
}
int main()
{
MyData x = test();
cout << x.my_string << x.my_value;
delete[] x.my_string;
}
There are other ways as well.
Thanks.
Yang
If string handling seems complicated to you (and it is very complicated)
then you should find out about the C++ string class, called std::string, it
will make things much easier for you because it does the memory allocation
for you.
E.g.
#include <string>
struct MyData
{
int my_value;
std::string my_string;
};
MyData test()
{
MyData d;
d.my_string = "abcdef";
d.my_value = 123;
return d;
}
int main()
{
MyData x = test();
cout << x.my_string << x.my_value;
}
Much simpler, and much more like your original code.
john
[note: some lines reformatted to fit within 80 columns.] so******@blue.s eas.upenn.edu (Yang Song) writes: HI, I am a little confused about char * and char[].
How would I be able to return a char* created in a function? Is new() the only way? How would I be able to return a point and a value at the same time? I thought of a possible solution. However, I am not quite sure if I understood char[] vs. char*. Any insight is greatly appreciated.
Here is the question: ---------------------- ...
char * test() { char[] buf = "abcdef"; return (char *)buf; }
int main() { char * p ; p = test(); // I know that this call is useless. So I tried to // modify the test() function to return the // char * properly. I listed my solution down // below. Please feel free to advise. return 0; }
----------------------
char * test (char * p) { p = new char[20]; p = "abcdef"; return p; }
int main() { char * p; char * value; value = test(p); cout << value << "\n"; }
Why not:
#include<string >
#include<ostrea m>
#include<iostre am>
using namespace std;
string test()
{
return "abcdef";
}
int main()
{
string value;
value= test()
cout << value << endl;
}
?
Others have already answered your questions about char* vs char[] . I
am telling you how to avoid those issues altogether.
"John Harrison" <jo************ *@hotmail.com> wrote in message
news:bj******** ****@ID-196037.news.uni-berlin.de...
If string handling seems complicated to you (and it is very complicated) then you should find out about the C++ string class, called std::string,
it will make things much easier for you because it does the memory allocation for you.
That is the truth. I can't understand why so many (more experienced) people
persist with char* string handling. It's probably the cause of more
programming bugs than any other single implementation element. Yes, I'm
aware of performance issues. I'm also aware that they used to use 2 digits
for the year to save space.
[note: some lines reformatted to fit within 80 columns.] so******@blue.s eas.upenn.edu (Yang Song) writes: HI, I am a little confused about char * and char[].
How would I be able to return a char* created in a function? Is new() the only way? How would I be able to return a point and a value at the same time? I thought of a possible solution. However, I am not quite sure if I understood char[] vs. char*. Any insight is greatly appreciated.
Here is the question: ---------------------- ...
char * test() { char[] buf = "abcdef"; return (char *)buf; }
int main() { char * p ; p = test(); // I know that this call is useless. So I tried to // modify the test() function to return the // char * properly. I listed my solution down // below. Please feel free to advise. return 0; }
----------------------
char * test (char * p) { p = new char[20]; p = "abcdef"; return p; }
int main() { char * p; char * value; value = test(p); cout << value << "\n"; }
Why not:
#include<string >
#include<ostrea m>
#include<iostre am>
using namespace std;
string test()
{
return "abcdef";
}
int main()
{
string value;
value= test()
cout << value << endl;
}
?
Others have already answered your questions about char* vs char[] . I
am telling you how to avoid those issues altogether. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Christopher Benson-Manica |
last post by:
I need a smart char * class, that acts like a char * in all cases, but
lets you do some std::string-type stuff with it. (Please don't say to
use std::string - it's not an option...). This is my attempt at it,
but it seems to be lacking... I'm aware that strdup() is nonstandard
(and a bad idea for C++ code) - please just bear with me:
/* Assume relevant headers are included */
class char_ptr
{
|
by: Alex Vinokur |
last post by:
"Richard Bos" <rlb@hoekstra-uitgeverij.nl> wrote in message news:4180f756.197032434@news.individual.net... to news:comp.lang.c
> ben19777@hotmail.com (Ben) wrote:
> > 2) Structure casted into an array of char
> > typedef struct {
> > char name;
> > int age;
> > int id;
> > } person;
> >
|
by: Sona |
last post by:
I understand the problem I'm having but am not sure how to fix it. My
code passes two char* to a function which reads in some strings from a
file and copies the contents into the two char*s. Now when my function
returns, the values stored in the char* are some garbage values (perhaps
because I didn't allocate any memory for them).. but even if I allocate
memory in the function, on the return of this function I see garbage..
here is my...
|
by: Peter Nilsson |
last post by:
In a post regarding toupper(), Richard Heathfield once asked me to think
about what the conversion of a char to unsigned char would mean, and whether
it was sensible to actually do so. And pete has raised a doubt in my mind
on the same issue.
Either through ignorance or incompetence, I've been unable to resolve some
issues.
6.4.4.4p6 states...
|
by: jab3 |
last post by:
(again :))
Hello everyone.
I'll ask this even at risk of being accused of not researching adequately.
My question (before longer reasoning) is: How does declaring (or defining,
whatever) a variable **var make it an array of pointers?
I realize that 'char **var' is a pointer to a pointer of type char (I hope).
And I realize that with var, var is actually a memory address (or at
| |
by: GRoll35 |
last post by:
I get 4 of those errors. in the same spot. I'll show my parent class,
child class, and my driver.
All that is suppose to happen is the user enters data and it uses
parent/child class to display it.
here is the 4 errors.
c:\C++\Ch15\Employee.h(29): error C2440: '=' : cannot convert from
'char ' to 'char '
|
by: Pedro Pinto |
last post by:
Hi there once more........
Instead of showing all the code my problem is simple.
I've tried to create this function:
char temp(char *string){
alterString(string);
return string;
|
by: Paul Brettschneider |
last post by:
Hello all,
consider the following code:
typedef char T;
class test {
T *data;
public:
void f(T, T, T);
void f2(T, T, T);
|
by: s0suk3 |
last post by:
This code
#include <stdio.h>
int main(void)
{
int hello = {'h', 'e', 'l', 'l', 'o'};
char *p = (void *) hello;
for (size_t i = 0; i < sizeof(hello); ++i) {
|
by: Kenzogio |
last post by:
Hi,
I have a struct "allmsg" and him member :
unsigned char card_number; //16
allmsg.card_number
|
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: 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...
|
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...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |