【发布时间】:2015-12-24 01:52:14
【问题描述】:
我正在使用字符串流来获取文本文件的内容(实际上,它是一个着色器代码源),以便将其传递给采用 const char* const* (glShaderSource) 的函数。起初,我是这样做的
std::stringstream buffer;
buffer << input.rdbuf();
char const *code = buffer.str().c_str();
glShaderSource(id, 1, &code, 0);
它不起作用,因为 code 的内容不是预期的。实际上,如果我这样做:
std::stringstream buffer;
buffer << input.rdbuf();
char const *code = buffer.str().c_str();
printf("Code*: %p\n", code);
printf("Buff*: %p\n", buffer.str().c_str());
printf("Code0: %c\n", code[0]); // ERROR: prints garbage.
printf("Buff0: %c\n", buffer.str().c_str()[0]);
printf("Code1*: %p\n", &code[1]); // ERROR: prints garbage.
printf("Buff1*: %p\n", &buffer.str().c_str()[1]);
printf("Code1: %c\n", code[1]);
printf("Buff1: %c\n", buffer.str().c_str()[1]);
我得到相同的指针值输出,缓冲区中字符的正确输出,但 code 内容的随机输出。
现在,如果我使用这样的功能:
void workaround(char const *code) {
printf("Code*: %p\n", code);
printf("Code: %s\n", code);
}
-------------------------------------
std::stringstream buffer;
buffer << input.rdbuf();
workaround(buffer.str().c_str());
printf("Buff*: %p\n", buffer.str().c_str());
printf("Buff: %s\n", buffer.str().c_str());
我得到了指针和字符串内容的正确值。
为什么这段代码有效,而不是第一个?
【问题讨论】:
-
你能详细说明有趣/意外吗?
-
无法复制:ideone.com/9G45jT
-
不要将解决方案放在问题中,将其作为答案发布。
-
有一个dreamlax发布的正确答案,但由于某种原因被删除了..
标签: c++ string pointers constants