C代码适用于Windows(使用Visual Studio编译)但不能在Linux上编译(使用gcc)

时间:2011-06-18 20:19:02

标签: c visual-studio gcc

我目前正在尝试为学校创建一个非常简单的C程序,它创建一个m整数n的数组(两者都由用户输入定义),并返回数组启动的位置或错误消息,如果无法创建数组。使用Visual Studio编译时,它运行得非常好,但是当我尝试使用gcc编译它时,它会抛出一堆错误消息,我根本不知道是什么导致它们。

源代码:

#include <stdio.h>
int *create_array(int n, int initial_value);

int main(){
    int *arr;
int num;
int numOfNum;

printf("Store this integer:\n");
scanf("%d", &num);

printf("Store the integer this amount of time:\n");
scanf("%d", &numOfNum);

arr = create_array(num, 1);

if(arr == NULL) printf("ERROR");
else printf("Array stored in this location: %p", arr);
    return 0;
}
int *create_array(int n, int initial_value){
int *pointer;
int i;

pointer = (int *) malloc(sizeof(int) * 10);

for(i = 0; i < n; i++){
    int *p;
    p = pointer;
    p += n*(sizeof(int));
    *p = initial_value;
    }

return pointer;
}

来自gcc的错误:

q1.c: In function âmainâ:
q1.c:18: error: missing terminating " character
q1.c:19: error: ânotâ undeclared (first use in this function)
q1.c:19: error: (Each undeclared identifier is reported only once
q1.c:19: error: for each function it appears in.)
q1.c:19: error: expected â)â before âbeâ
q1.c:19: error: missing terminating " character
q1.c:20: error: missing terminating " character
q1.c:21: error: missing terminating " character
q1.c:39: error: expected declaration or statement at end of input

2 个答案:

答案 0 :(得分:8)

看到奇怪的字符“ânotâ”我怀疑你使用的是错误的文件编码。尝试将代码粘贴到linux文件编辑器中,并将其从该编辑器保存到新文件中。尝试编译它。

答案 1 :(得分:1)

您的代码与发布时完全一样,使用我的gcc生成这些消息

6398652.c:4:5: error: function declaration isn’t a prototype [-Werror=strict-prototypes]
6398652.c: In function ‘main’:
6398652.c:4:5: error: old-style function definition [-Werror=old-style-definition]
6398652.c:18:3: error: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int *’ [-Werror=format]
6398652.c: In function ‘create_array’:
6398652.c:25:3: error: implicit declaration of function ‘malloc’ [-Werror=implicit-function-declaration]
6398652.c:25:21: error: incompatible implicit declaration of built-in function ‘malloc’ [-Werror]
cc1: all warnings being treated as errors

此更改版本编译干净

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

int *create_array(int n, int initial_value);

int main(void) {
  int *arr;
  int num;
  int numOfNum;

  printf("Store this integer:\n");
  scanf("%d", &num);

  printf("Store the integer this amount of time:\n");
  scanf("%d", &numOfNum);

  arr = create_array(num, 1);

  if (arr == NULL) {
    printf("ERROR\n");
  } else {
    printf("Array stored in this location: %p\n", (void*)arr);
  }
  return 0;
}

int *create_array(int n, int initial_value) {
  int *pointer;
  int i;

  pointer = malloc(10 * sizeof *pointer);

  for (i = 0; i < n; i++) {
    int *p;
    p = pointer;
    p += n*(sizeof *p);
    *p = initial_value;
  }

  return pointer;
}