我有一个int *arr[3];
数组,其元素像这样初始化:
sides[0] = &a;
sides[1] = &b;
sides[2] = &c;
其中a = b = 5和c = 10。现在,当我尝试强制转换每个指针指向的内存地址的内容的值的类型(从int到double)时,第3个值始终显示为0。您知道为什么吗?
这就是我在做什么:
double a,b,c;
a = (double) *sides[0];
b = (double) *sides[1];
c = (double) *sides[2];
printf("%lf %lf %lf",a,b,c);
我得到的output
是:
5.0000 5.0000 0.0000
这是完整的代码:
#include <stdio.h>
#include <math.h>
void populateSides(int *[3]);
void calculateTriangleType(int *[3]);
/*
* Function populateSides: Has 1 arg
* 1st arg: an array of int *.
* This function stores the 3 sides of a triangle
* given by the user into the sides array.
*/
void populateSides(int *sides[]) {
int i,a,b,c;
scanf(" %d",&a);
scanf(" %d",&b);
scanf(" %d",&c);
while((c <= b) || (c <= a)) {
scanf(" %d",&c);
}
sides[0] = &a;
sides[1] = &b;
sides[2] = &c;
}
/*
*/
void calculateTriangleType(int *sides[]) {
double a,b,c;
a = (double) *sides[0];
b = (double) *sides[1];
c = (double) *sides[2];
printf("%lf %lf %lf",a,b,c);
}
int main(void) { // Stelios Papamichail 4020
int *sides[3]; // stores each side of a triangle ( >0)
populateSides(sides);
calculateTriangleType(sides);
return 0;
}