我在尝试理解指针时遇到了一个非常令人沮丧的时间,实际上我在编码时遇到的 90% 的错误都完全围绕着指针
所以我有一个 char* 数组,mallocced 和 holding 字符
strcpy 出于某种原因只接受指针,所以如果我想将 array[x] strcpy 到目的地,我不能只使用
strcpy(destination,array[x])
因为这给了我一个错误,说 array[x] is a char, not a char*
现在这是我不明白的事情——我如何创建一个指向数组 [x] 的指针?我完全不懂指针
当我使用
char i;
char *j;
i = array[0];
j = &i;
strcpy(destination,j);
它给了我这封信,但伴随着垃圾字符,尽管我在将它分配给 &i 之前已经设置了 j
当我使用
char *j;
j = &array[0];
strcpy(destination,j);
它添加了整个数组
有什么区别?在这两种情况下,我都将 J 分配给 x[0] 的地址,不是吗?
最佳答案
您已经忘记了变量的位置以及您正在复制的内容。这是您的代码,注释了它在做什么。
char i; // reserves a variable of size char on the stack
char *j; // reserves a variable of size ptr on the stack
i = array[0]; // copies the first char from the array
// into variable i
j = &i; // copies the stack address of variable i into j..
// note that this is not the array as we
// previously copied the char out of the array
strcpy(destination,j); // you have not supplied destination, so
// no comment there but j is a pointer
// onto the stack AND NOT a pointer
// into the array.. thus who knows
// what characters it will copy afterwards
版本 2 的不同之处在于:
char *j; // reserves a variable on the stack of size ptr
j = &array[0]; // sets the contents of variable j to the address
// of the first element of the array.. note
// that this is the same as `j = array`
strcpy(destination,j); // starts copying the chars from j into
// destination, incrementing the pointer j
// one at a time until a null is found and
// the copying will stop
所以总而言之,版本 2 正在复制数组。而版本 1 是在将数组的第一个字符复制到堆栈后从堆栈复制数据。因此行为不同。
关于c - 只是无法理解指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145056/