实际上,当我使用指向字符的指针时,memcpy 工作得很好,但当我使用指向字符的指针时,它就停止工作了。
有人可以帮助我理解为什么 memcpy 在这里失败,或者更好的是,我是如何自己解决的。我发现很难理解我的 c/c++ 代码中出现的问题。
char *pc = "abcd";
char **ppc = &pc;
char **ppc2 = &pc;
setStaticAndDynamicPointers(ppc, ppc2);
char c;
c = (*ppc)[1];
assert(c == 'b'); // assertion doesn't fail.
memcpy(&c,&(*ppc[1]),1);
if(c!='b')
puts("memcpy didn't work."); // this gets printed out.
c = (*ppc2)[3];
assert(c=='d'); // assertion doesn't fail.
memcpy(&c, &(*ppc2[3]), 1);
if(c != 'd')
puts("memcpy didn't work again.");
memcpy(&c, pc, 1);
assert(c == 'a'); // assertion doesn't fail, even though used memcpy
void setStaticAndDynamicPointers(char **charIn, char **charIn2)
{
// sets the first arg to a pointer to static memory.
// sets the second arg to a pointer to dynamic memory.
char stat[5];
memcpy(stat, "abcd", 5);
*charIn = stat;
char *dyn = new char[5];
memcpy(dyn, "abcd", 5);
*charIn2 = dyn;
}
最佳答案
您的评论暗示 char stat[5]
应该是静态的,但事实并非如此。结果 charIn
指向分配在堆栈上的 block ,当您从函数返回时,它超出了范围。您是说 static char stat[5]
吗?
关于c - memcpy 失败但赋值不在字符指针上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4072821/