我是学习指针的初学者。这是我的代码。 (注:我仍然在试图让我的头周围的指针,所以我的代码不会是干净的。)C编程简单指针
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]){
int a = 1;
char b = 's';
double c = 3.14;
int *ptra;
int *ptrb;
int *ptrc;
ptra = &a;
ptrb = &b;
ptrc = &c;
printf("I initialised int as %d and char as %c and double as %.2f\n", a, b, c);
printf("The address of A is %p and the contents of A is %d\n", ptra, *ptra);
printf("The address of B is %p and the contents of B is %c\n", ptrb, *ptrb);
printf("The address of C is %p and the contents of C is %.2f\n", ptrc, *ptrc);
我期待下面的输出:
I initialised int as 1 and char as s and double as 3.14
The address of A is 0xbf933094 and the contents of A is 1
The address of B is 0xbf933093 and the contents of B is s
The address of C is 0xbf933098 and the contents of C is 3.14
而是我得到这个:
I initialised int as 1 and char as s and double as 3.14
The address of A is 0xbf933094 and the contents of A is 1
The address of B is 0xbf933093 and the contents of B is s
The address of C is 0xbf933098 and the contents of C is 427698.00000
有人可以帮我打印C的内容时得到的大数?为什么我不能得到3.14? (这个数字实际上比这个长,但它不适合这个文本框。:-))
我想你想要一个双指针,而不是int。 –
我有一种感觉,它与指针'ptrc'设置为指向'int'数据类型的事实有关,但实际上它指向了'double'数据类型。 “int”通常是4个字节,“double”是8个字节。指针正在查看4个字节的信息,但它必须读取所有8个字符才能获得'double'的真实值。为了“解决”问题,将'ptrc'声明为'double'。 – brazilianldsjaguar
这里的大多数答案都没有提到。发生此问题的原因是sizeof(double)> sizeof(int),导致浮点值尾数中的位被截断。 –