gpt4 book ai didi

c - 指针指向不同的数据类型

转载 作者:行者123 更新时间:2023-11-30 21:22:38 25 4
gpt4 key购买 nike

我读到如果我们使用指针,数据类型必须相同。但我测试过这段代码,没有错误。我认为那里会有一个错误。但什么也没发生。该程序按其应有的方式运行。为什么我们可以解释这一点?

代码:

#include<stdio.h>

int main(){
float i, j, k, l;
int *c1, *c2, c[1];

printf("Enter i : ");
scanf("%f", &i);
printf("Enter j : ");
scanf("%f", &j);
printf("Enter k : ");
scanf("%f", &k);
printf("Enter l : ");
scanf("%f", &l);

c1 = &c[0];
*c1 = i+k;
c2 = &c[1];
*c2 = j+l;
printf("\nMatrice c is [%d ; %d]\n", *c1, *c2);

return 0;

}

输出:

Enter i : 1
Enter j : 2
Enter k : 3
Enter l : 4

Matrice c is [4 ; 6]

Process returned 0 (0x0) execution time : 1.447 s
Press any key to continue.

我编辑了这段代码

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.

最佳答案

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)

在您的代码中,问题是数组大小不够。没有元素 c[1],因此行为未定义。

这最常导致段错误,但你不走运。

将数组c声明为int c[2];

另外,请注意 [] 运算符的作用。
如果您定义一个变量,它会显示该数组将容纳多少元素 - 应分配多少内存。

在表达式array[N]中与*(array + N)相同

关于c - 指针指向不同的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52856951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com