1

I am new to C, and I am trying to initialize array elements at run time, according to user input (so if the user inputs 4, then array[0]=4).

I have the following code:

#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;
}

The code compiles, but triggers an access violation. What's wrong?

3
  • 2
    You should be passing the address of n to scanf(). Commented Apr 1, 2015 at 23:28
  • 3
    Please try to find the flags that allow the compiler you use to warn you about such problems. With GCC, a sensible option to use is -Wall to catch a large variety of such errors. Other compilers will probably need other options. Commented Apr 1, 2015 at 23:30
  • I forgot about the address of operator. Thanks to everyone. Commented Apr 1, 2015 at 23:47

1 Answer 1

2

You should be passing &n to scanf.

scanf("%d", &n);

As Jonathan pointed out, this is easily caught by a compiler warning. For gcc you can use -Wall which will show you:

warning: format specifies type 'int *' but the argument has type
  'int' [-Wformat]
scanf("%d", n); //asks for array value
       ~~   ^ 
Sign up to request clarification or add additional context in comments.

1 Comment

I totally forgot about the address of operator! Such a noob mistake. Code works now. Thanks for your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.