-1

Memcpymemcmp函数可以带一个指针变量吗?

char *p;
char* q;
memcpy(p,q,10); //will this work?
memcmp(p,q,10); //will this work?
4

1 回答 1

1

不,您编写的代码将不起作用,因为您将未初始化的指针传递给memcpy()(and memcmp(),但memcpy()调用就足够了)。这将导致未定义的行为,因为您不允许从这些“随机”位置读取/写入。

您可以通过确保指针有效来修复它,例如:

char buf[10], *p = buf;
const char *q = "hello hello";

memcpy(p, q, 10);
printf("the copying made the buffers %s\n",
  memcmp(p, q, 10) == 0 ? "equal" : "different");

当然p可以换成刚才的plainbuf上面。

于 2015-02-24T14:33:46.453 回答