-
LPSTR problem
I created a method to get a file in the current directory:
Code:
LPSTR CApplication::GetFile(LPSTR File)
{
char Path[1000];
GetModuleFileName(m_hInst,Path,1000);
for(UINT x=(UINT)strlen(Path);x>0;x--)
if(Path[x]=='\\')
break;
Path[x+1]='\0';
strcat(Path,File);
LPSTR ReturnPath=Path;
return ReturnPath;
}
When I request a file the method returns a string, which can be shown by a messagebox, but when I try to write it to a file I get:
Code:
08 11 F4 77 1E (hex)
what am I doing wrong?
thanks in advance,
borre mosch
-
>char Path[1000];
Okay so far.
>LPSTR ReturnPath=Path;
Still okay, but very foreboding.
>return ReturnPath;
Aaaahh! My eyes! ;) You're returning a pointer to a local array. When the function returns, the memory for Path is released so you can no longer reference it. Maybe something like this would fix that particular problem, but your function is still suspect:
Code:
LPSTR CApplication::GetFile(LPSTR File)
{
char *Path = new char[1000];
GetModuleFileName(m_hInst,Path,1000);
for(UINT x=(UINT)strlen(Path);x>0;x--)
if(Path[x]=='\\')
break;
Path[x+1]='\0';
strcat(Path,File);
return Path;
}
-
Post code for the writing to file. You may be writing the address of the pointer, not the content stored at the address of the pointer, to the file.
-
well yes I guess I AM writing the pointer to the file, but is there any way to make the function return a string and not a pointer, other than using a global variable?
By the way I still wonder why the messagebox function is capable of showing the message which' memory was actually delocated when the fwrite function doesn't
-
one way:
pass the pointer to the array into the function. So that it is allocated in the caller
second way: allocate dynamically, pass it out
third way: use a string class. Make the return value of type string. It'll be copied into the return value.
-
I tried to pass a pointer to the variable to the function, but it didn't really work out...can anyone give an example of such a function?
-
>can anyone give an example of such a function?
Code:
void callee(char buffer[], size_t size);
void
caller()
{
char buffer[BUFSIZ];
fill0(buffer, sizeof buffer);
...
}
void
fill0(
char buffer[],
size_t size
)
{
for (size_t i = 0; i < size; i++) {
buffer[i] = 0;
}
}