2015-04-01 35 views
1

我是C新手,我试图在运行时根据用户输入初始化数组元素(所以如果用户输入4,那么array [0] = 4)。在运行时初始化数组元素

我有以下代码:

#include<stdio.h> 
#define MAX 10 
#define maxValue 100 

int array[MAX]; 
int n; 
int main(void){ 
    scanf("%d", n); //asks for array value 
    if (n <= maxValue) 
    { 
     array[0] = n; 
    } 
    return 0; 
} 

代码编译,但触发访问冲突。 有什么问题?

+3

'的scanf( “%d”,&n);' – 2015-04-01 23:27:58

+2

你应该n的地址传递给'scanf()的' – 2015-04-01 23:28:05

+3

请尝试找到标志。它允许你使用的编译器向你发出这样的问题警告:使用GCC,一个明智的选择是使用'-Wall'来捕获大量这样的错误,其他的编译器可能需要其他的选项 – 2015-04-01 23:30:56

回答

2

您应该将& n传递给scanf。

scanf("%d", &n); 

正如乔纳森指出的那样,这很容易被编译器警告捕获。对于GCC,你可以使用-Wall它会告诉你:

warning: format specifies type 'int *' but the argument has type 
    'int' [-Wformat] 
scanf("%d", n); //asks for array value 
     ~~ ^
+0

我完全忘记了运营商的地址!这样一个noob错误。代码现在工作。感谢您的帮助。 – 2015-04-01 23:44:21