使用指针编译C程序时出错

时间:2012-01-16 19:20:20

标签: c pointers

当我在计算机上运行时,出现编译错误。但是,我确实从我在互联网上找到的教程中直接复制了它。

#include <stdio.h>
#include <conio.h>

void main(){
    int i = 9;
    clrscr();

    printf("The value of i is: %d\n", i);
    printf("The address of i is: %u\n", &i);
    printf("The value at the address of i is: %d\n", *(&i));

    getch();
}

错误:

$ cc "-Wall" -g    ptrex6.c   -o ptrex6
ptrex6.c:7:19: error: conio.h: No such file or directory
ptrex6.c:9: warning: return type of ‘main’ is not ‘int’
ptrex6.c: In function ‘main’:
ptrex6.c:11: warning: implicit declaration of function ‘clrscr’
ptrex6.c:14: warning: format ‘%u’ expects type ‘unsigned int’, but argument 2 has type ‘int *’
ptrex6.c:17: warning: implicit declaration of function ‘getch’
make: *** [ptrex6] Error 1

4 个答案:

答案 0 :(得分:7)

错误:

  1. conio.h不是标准C标头。它可能在您的系统上不可用。然而,printf()不需要它。这就是stdio.h在这里的原因。删除它,并删除clrscr()。没有conio库,它将无法工作。通过这样做,您将能够编译您的文件,因为其他消息是“只是”警告,而不是错误。

  2. main()函数的返回类型更改为int并返回0.这就是C标准指定的内容。 你想要这个。

  3. 使用%d格式说明符代替%u。正如编译器消息直接指出的那样,%u用于无符号整数,int是显式签名的。对于整数&gt; = 2 ^ 31,您将遇到奇怪的行为问题。

  4. 您再次使用错误的说明符。使用%p表示地址/指针,而不是%u /%d / whatever。

  5. 不要明确地相信/复制粘贴教程。教程不适用于复制粘贴,而是要考虑和学习它们。

答案 1 :(得分:4)

你必须使用一本相当旧的书/例子。 conio.h文件用于MS-DOS系统。您的代码应如下所示:

#include <stdio.h>

int main()
{
    int i = 9;

    printf("The value of i is: %d\n", i);
    printf("The address of i is: %p\n", (void*)&i);
}

答案 2 :(得分:3)

以下是如何在C:

中打印指针值
printf("The address of i is: %p\n", (void *) &i);

答案 3 :(得分:2)

Wikipedia

所述
  

conio.h是旧的MS-DOS编译器中用于创建文本的C头文件   用户界面。它没有在C编程语言中描述   本书,不是C标准库的一部分,ISO也不是   由POSIX 定义。