-
pointers question
How to fix this program so name = "TEST"
and why doesn't it work now?
output now is:
TEST ... in prompt()
x ... in main()
Press any key to continue
Thank you!
Vera
-----
#include <iostream.h>
struct S
{
char *name;
};
char* prompt()
{
char str[]="TEST";
cout << &str[0] << " ... in prompt()\n";
return &str[0];
}
void init(S *s)
{
s->name = prompt();
}
void main()
{
S s;
init(&s);
cout << s.name << " ... in main()\n";
}
-
Well at first glance the problem appears to be in your prompt() function. It should look more like this:
Code:
char prompt(void)
{
char str[]="TEST";
cout << str[0] << " ... in prompt()\n";
return str[0];
}
I changed the function so that it returns a char, since that is all that you were doing before but perhaps you wanted your function to return the whole string. If so just have it return the char* and return str. Lose the "&" in the call to init too. You don't seem to understand how to use them properly so read up on that. Bye the way, unless the struct in the code you are using has some other variables to it then it is entirely unnecessary to make a struct that only has one variable in it.
-
h
Well... first of all, int C++ 'char*' does not mean 'string', as he said u should read up on pointers. you need to allocate some chars t othat pointer:
pointer = new char[255];
*pointer = "Hello World";
or
sprintf(pointer,"blah");
SPH
-
How do i return a char[] and then assign it to
name?
char* prompt()
{
char str[] ="TEST";
return str;
}
warning C4172: returning address of local variable or temporary
Thank you
Vera
-
You can not pass a local array that is declared on the function stack to the caller. The memory will go out of scope. Also you must malloc the memory in your structure in order to store a string. And use the keyword 'struct' based on you declaration syntax:
Code:
#include <iostream>
using namespace std;
struct S
{
char *name;
};
char* prompt()
{
char *str = new char[5];
strcpy(str,"TEST");
cout << str << " ... in prompt()\n";
return str;
}
void init(struct S *s)
{
s->name = prompt();
}
void main()
{
//note the word struct
struct S s; //could have just done struct S *s;
init(&s); //than init(s);
cout << s.name << " ... in main()\n";
delete [] s.name;
}