C编程简单指针

Bob*_*bby 2 c pointers

我是学习指针的初学者.这是我的代码.(注意:我仍然试图绕过指针,所以我的代码不干净.)

#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);
Run Code Online (Sandbox Code Playgroud)

我期待以下输出:

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
Run Code Online (Sandbox Code Playgroud)

但相反,我得到了这个:

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
Run Code Online (Sandbox Code Playgroud)

在打印C的内容时,有人可以为我获得的大量数据提供帮助吗?为什么我得不到3.14?(这个数字实际上比这长,但它不适合这个文本框.:-))

det*_*tly 5

你是在宣告ptra,ptrb也是s的ptrc指针int.但是指针的类型是基于它所指向的,所以它应该是:

int    *ptra;
char   *ptrb;
double *ptrc;
Run Code Online (Sandbox Code Playgroud)

在您的特定情况下,您的程序正在尝试double通过int指针解释值.由于这些数据类型的大小在您的机器上有所不同,因此双倍的某些位被丢弃,您最终得到了您所看到的奇怪数字.

这可能并不总是以相同的方式发生 - 通过错误类型的指针访问某些内容的结果不是由C语言定义的,但它仍然可以编译.C程序员将此称为未定义的行为(如果你想学习C,你应该真正接受这个术语!).

还有一个事实是,当您调用时printf,您需要从格式字符串中为其提供所需类型的变量.所以,如果你给它一个格式字符串,其中第占位符%.f,你必须给它,这是一个双重的第一参数.如果你不这样做,printf也会表现出未定义的行为并且可以做任何事情(未定义的行为可能是奇怪的输出,崩溃,或者只是输出你期望的数字......直到最糟糕的时刻).