c - 编译困难 : Pointers in C

标签 c pointers

我已经用 Java 编程一年多了,但在大学学习的同时,我正在慢慢地自学 C/ObjectiveC:《Cocoa 和 Objective C - 启动和运行》一书。我仍在阅读介绍性章节,熟悉 C 与 Java 的语法差异,并且遇到了关于动态内存的部分,特别是关于指针的部分。它提供的示例是这样的:

#include <stdio.h>
#include <stdlib.h>
int* numbers;
numbers = malloc ( sizeof(int) * 10);

//create a second variable to always point at the 
//beginning of numbers memory block
int* numbersStart;
numbersStart = numbers;

*numbers = 100;
numbers++;
*numbers = 200;

//use the 'numbersStart' variable to free the memory instead
free( numbersStart );

我理解代码 - 创建一个整数指针,为其分配 10 个内存块,创建第二个指针指向第一个数字动态内存块,将第一个 block 设置为 100,递增到第二个 block 并设置到 200,然后使用 free() 释放内存。

但是,当我尝试编译时,出现一系列错误。该代码保存在名为 Dynamic 的文件夹中名为 Dynamic.c 的 c 类中。

这是终端中发生的情况的打印:

    gcc Dynamic.c -o Dynamic
    Dynamic.c:13: warning: data definition has no type or storage class
    Dynamic.c:13: error: conflicting types for ‘numbers’
    Dynamic.c:12: error: previous declaration of ‘numbers’ was here
    Dynamic.c:13: warning: initialization makes integer from pointer without a cast
    Dynamic.c:13: error: initializer element is not constant
    Dynamic.c:15: warning: data definition has no type or storage class
    Dynamic.c:15: error: conflicting types for ‘numbersStart’
    Dynamic.c:14: error: previous declaration of ‘numbersStart’ was here
    Dynamic.c:15: error: initializer element is not constant
    Dynamic.c:16: warning: data definition has no type or storage class
    Dynamic.c:16: warning: initialization makes pointer from integer without a cast
    Dynamic.c:17: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘++’ token
    Dynamic.c:18: warning: data definition has no type or storage class
    Dynamic.c:18: error: redefinition of ‘numbers’
    Dynamic.c:16: error: previous definition of ‘numbers’ was here
    Dynamic.c:18: warning: initialization makes pointer from integer without a cast
    Dynamic.c:19: warning: data definition has no type or storage class
    Dynamic.c:19: warning: parameter names (without types) in function declaration
    Dynamic.c:19: error: conflicting types for ‘free’
    /usr/include/stdlib.h:160: error: previous declaration of ‘free’ was here

如果有人可以解释为什么会发生这些错误,我将非常感激,我不明白为什么它们应该作为书中的示例。

谢谢。

最佳答案

那个程序不好。您至少需要一个 main() 函数。添加:

int main(void)
{

#include行之后添加:

  return 0;
}

最后,它将编译。

关于c - 编译困难 : Pointers in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9572806/

相关文章:

c - 使用 fputs() 将整数写入文件

c - 结构变量初始化的问题

c - 使用快速排序对字符数组进行排序

c - 为什么我能够像这样将新字符串重新分配给 C 中的 char 指针(ch *string = "hello"; string = "assign";)

c - 如何在c中定义 '\n'之后的空格数

c - 在 C 中复制 Strlen 函数

c - 程序中出现段错误,但 GDB 不显示行号

c++ - vector 指针和 push_back()

我可以使用 main 中 argc 的地址作为随机源吗?

c++ - 如何从原始 Ptr 增加共享 Ptr 的计数