c - 只是无法理解指针

标签 c arrays pointers

我在尝试理解指针时遇到了一个非常令人沮丧的时间,实际上我在编码时遇到的 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/

相关文章:

c++ - 访问冲突写入位置 0x00000000。指针问题

python - 如何拆分数组,然后在 0 和第 N 个值之间追加数组,然后在下一组中重复相同的步骤?

c - 在 C 程序中获取(星号)作为输入

c - "array/pointer equivalence"的现代术语是什么?

c - 为什么 printf() 对于大整数输出 -1?

Java > Array-2 > ZeroMax

arrays - 如何在Kotlin中将对象, bool 值和long值添加到数组中?

c - 成功调用 fseek() 函数会清除流的文件结束指示器

c++ - 指针可以指向一个值,指针值可以指向地址吗?

python - 在Python中调用C函数并返回2个值