问题描述
那我该怎么做才能获得正确的代码?
What should I do to have a correct code then ?
好的,我更正下面的代码
Ok, I correct the code below
摆弄memcpy.Linux,64位.gcc 4.8.x
Fiddling with memcpy.Linux, 64 bits.gcc 4.8.x
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void d(char ** restrict a, char ** restrict b){
char r[20];
memcpy(r,*a, strlen(*a)+1);
// it is the same thing as before since *c is equivalent to &r (or put simply r).
char *restrict c = malloc(20);
memcpy(c,*a, strlen(*a)+1);
// that one bugs me. why b alone and not *b ??
// EDIT : this is incorrect
memcpy(b,*a, strlen(*a)+1);
// EDIT : this is correct
memcpy(*b,*a, strlen(*a)+1);
printf("pointer c -> hey %s\n",c);
printf("array r -> hey %s\n",r);
// EDIT : this is incorrect
printf("double pointer -> hey %s\n",b);
// EDIT : this is correct
printf("double pointer -> hey %s\n",*b);
}
int main(void)
{
char a[] = "YOU";
char * b = a;
char * c = malloc(20);
d(&b, &c);
return 0;
}
问题
我想了解为什么memcpy不会抱怨我将双指针传递给它,而只需要一个指针.
Question
I would like to undertsand why memcpy doesn't complain about me passing double pointer to it, while it needs a pointer only.
我知道使用chars * b ==& a == a,并且数组的第一个成员引用的数组最多为'\ 0'.问题确实在于将双指针传递给memcpy.
I know that with chars *b == &a == a and that an array is referenced by its first member up to '\0'. The problem really is with passing a double pointer to memcpy.
我为什么不必做
memcpy(*b, *a, strlen(*a)+1);
因为memcpy签名是
since memcpy signature is
void * memcpy ( void * destination, const void * source, size_t num );
,根据 cplusplus.com .
请问这里的渔获物"是什么?
What is the "catch" here please ?
非常感谢
推荐答案
双指针是指向单个指针的单个指针,因此可以将其传递给需要空指针的函数.
Well, a double pointer is a single pointer to single pointer, so it can be passed to a function that expects a void pointer.
您的代码是否正确,当然是另一回事...并非如此,并且仅出于巧合.请注意,不仅您使用memcpy()写入了错误的位置,而且还打印了与printf()中的字符串相同的错误内存位置.这里的巧合"是这两个错误"位置都相同,因此您错误地认为它可以正常工作.
It is of course another thing whether or not your code is correct... It's not and works only by coincidence. Note that not only you use memcpy() to write to a wrong location, but you also print the same wrong location of memory as a string in your printf(). The "coincidence" here is that both of these "wrong" locations are the same, so you falsely assumed that it works fine.
尝试真正打印正确的东西,您会看到混乱的地方:
Try to really print the right thing and you'll see the mayhem:
printf("double pointer -> hey %s\n",*b);
这篇关于c-memcpy和指针.仍在工作.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!