• Advertisement

Archived

This topic is now archived and is closed to further replies.

char pointers

This topic is 5560 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I origonally had this:
char *path = "images\\";
loadBMP( strcat(path, "image.bmp") );
 
and got an access violation. I figured that strcat would have tried to copy "image.bmp" into the end on path, and wouldnt have had enough space. So I tried this:
char *path = new char[50];
path = "images\\";
loadBMP( strcat(path, "image.bmp") );
 
The call to strcat still throws an access violation. Why is this? How should I be doing this? Thanks

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
char *path = new char[50];
// path points now to a char array of length 50
path = "images\\";
// the char array is lost with a memory leak.
// path now points to the newly allocated string "images\"
loadBMP( strcat(path, "image.bmp" );

The correct way to assign a value to a string is with
strcpy(path, "images\\";
Alternatively, you might want to use the string class, but that''s an item of personal preference and designe needs.

Share this post


Link to post
Share on other sites
quote:
Original post by doogle
char *path = "images\\";


That should be
const char *path = "images\\";

Which would rightfully give you a compiler error with what you are trying. You can only declare it non-const via a piece of backward compatible bogosity.
quote:

So I tried this:

char *path = new char[50];
path = "images\\";
loadBMP( strcat(path, "image.bmp") );


That causes exactly the same problem, plus a leak. Since you are working with pointer types, the "=" operator is actually assigning pointers, not c-strings.

To do what you actually want, try this:


  
#include <string>

int main()
{
std::string path = "images\\";
loadBMP(path + "image.bmp");
};


And write an overload of loadBMP which takes a std::string.

Share this post


Link to post
Share on other sites

  

#include <cstring>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
char path[50] = "images\\";

cout << strcat(path, "image.bmp");

return 0;
}



this worx

Share this post


Link to post
Share on other sites
or instead of overloading


  
#include <string>

int main()
{
std::string path = "images\\";
std::string pathAndFile = path + "image.bmp";
loadBMP(pathAndFile.c_str());
return 0;
}


just an option

[edited by - petewood on December 5, 2002 7:50:36 AM]

Share this post


Link to post
Share on other sites
Ok thanks everybody for their replies.

I think I have got it all working now

Share this post


Link to post
Share on other sites

  • Advertisement