Борьба с компиляцией: указатели в C - PullRequest
2 голосов
/ 05 марта 2012

Я программирую на java уже больше года, но медленно учу себя C / targetC, пока учусь в универе из книги: Какао и Objective C - Up and Running.Я все еще прохожу вводные главы, знакомлюсь с синтаксическими различиями в 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 блоков памяти, создайте второй указатель, чтобы указать на первый блок чисел динамической памяти, установитепервый блок до 100, увеличивайте до 2-го блока и установите его на 200, затем используйте free () для освобождения памяти.

Однако, когда я пытаюсь скомпилировать, я получаю серию ошибок.Код сохраняется в классе ac с именем Dynamic.c в папке с именем dynamic.

Вот распечатка того, что происходит в терминале:

    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

Если кто-то может объяснить, почему происходят эти ошибкиЯ был бы очень признателен, я не понимаю, почему они должны быть в качестве примера из книги.

Спасибо.

Ответы [ 4 ]

3 голосов
/ 05 марта 2012

Эта программа не годится. Вам нужна как минимум функция main(). Добавить:

int main(void)
{

Сразу после строки #include и добавьте:

  return 0;
}

в самом конце, и он скомпилируется.

1 голос
/ 05 марта 2012

Оберните это в main() функцию:

#import <stdio.h>
#import <stdlib.h>

int main()
{
    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 );

    return 0;
}
0 голосов
/ 05 марта 2012
numbers = malloc ( sizeof(int) * 10);

Это оператор, и вы не можете иметь оператор вне функции в C.

Организуйте свою программу с помощью функций и поместите операторы в тело функций.Это правильно:

// This defines a function named foo that takes no argument and returns no value 
void foo(void)
{
    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 );
}
0 голосов
/ 05 марта 2012

Вам необходимо определить функцию main:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int* numbers; 
  numbers = malloc ( sizeof(int) * 10);
  ...  
  free( numbersStart );
  return EXIT_SUCCESS; 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...