I know this sounds like a beginner question but I have never worked with char* in c++. I always just used strings. But there is a bug with Ubuntu 13.10
and the NVidia
OpenGL
drivers so I have to use char*. Here is the bug.
I have a class that takes a const char* folderName
in the constructor and then creates compiles all the .glsl
files in the folder. I have tried strcpy
and strcat
and they both seem so override.
glProgram *p = new glProgram("phong\n");
glProgram :: glProgram(const char* folderName)
{
cout << folderName << endl;
char* name = strdup(folderName);
cout << name << endl;
name = strcat(name,"/vertex.glsl");
cout << name << endl;
}
But the output is not as expected.
phong
phong
/vertex.glsl
How can I get the output to be phong/vertex.glsl
?
The code is invalid because you overwrite memory that does not belong to the dynamically allocated array. You should yourself allocate a memory region large enough to contain the concatenated string.
glProgram *p = new glProgram("phong\n");
glProgram :: glProgram(const char *folderName)
{
const char *vertex = "/vertex.glsl";
size_t n = std::strlen( folderName );
if ( n != 0 && folderName[n - 1] == '\n' ) --n;
char *name = new char[n + std::strlen( vertex ) + 1];
std::strncpy( name, folderName, n );
name[n] = '\0';
std::strcat( name, vertex );
}
Also I do not see any sense that the argument includes the new line character. Why may not the argument look as "phong"
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.