C 指针指向不同的数据类型
我读到,如果我们使用指针,数据类型必须相同。但是我已经测试了这段代码,没有错误。我想那里会有一个错误。但什么也没发生。该程序的工作原理与它应该的一样。为什么我们可以解释这一点 代码: 我已经编辑了这个代码C 指针指向不同的数据类型,c,arrays,pointers,C,Arrays,Pointers,我读到,如果我们使用指针,数据类型必须相同。但是我已经测试了这段代码,没有错误。我想那里会有一个错误。但什么也没发生。该程序的工作原理与它应该的一样。为什么我们可以解释这一点 代码: 我已经编辑了这个代码 printf("\nMatrice c is [%d ; %d]\n", *c1, *c2); 成为 printf("\nMatrice c is [%f ; %f]\n", *c1, *c2); 并且输出是错误的 Enter i : 1 Enter j : 2 Enter k : 3 E
printf("\nMatrice c is [%d ; %d]\n", *c1, *c2);
成为
printf("\nMatrice c is [%f ; %f]\n", *c1, *c2);
并且输出是错误的
Enter i : 1
Enter j : 2
Enter k : 3
Enter l : 4
Matrice c is [0.000000 ; 42581666233418238000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000]
Process returned 0 (0x0) execution time : 1.164 s
Press any key to continue.
在代码中,问题是数组大小不够。
没有元素c[1],因此行为未定义
这通常会导致分割错误,但您很不走运
将数组c声明为int c[2]
另外,请注意[]运算符的作用。
如果您定义了一个变量,它将显示这个数组将容纳多少元素—应该分配多少内存
表达式中的数组[N]与*array+N相同c2=&c[1];-没有c[1]。您的代码在取消c2引用时调用未定义的行为。数组c有一个元素,并且使用基于零的索引,这意味着c[0]是可行的。c[1]不是。数组索引从0开始。那么,当数组大小为1???@WhozCraig时,如何才能访问c[1],因此我必须更改变量c[1]?如果数组大小为n,则可以从0访问到n-1。是的,为了访问c[0]和c[1],数组大小必须为c[2]
printf("\nMatrice c is [%f ; %f]\n", *c1, *c2);
Enter i : 1
Enter j : 2
Enter k : 3
Enter l : 4
Matrice c is [0.000000 ; 42581666233418238000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000]
Process returned 0 (0x0) execution time : 1.164 s
Press any key to continue.
int* c1; //pointer to int
int c[1]; //int array with one element
c1 = &c[0]; // c1 points to the the first and only element of the array.
c[0] = 5; // the first element of the array c is 5
*c1 = 5; // The element to which the pointer is pointing is 5 (dereferencing)