0
#include <cs50.h>
#include <stdio.h>


int example[];
int main(void)
{
    int example = {1,2,3};

    for (int i = 0; i < 3; i++) {
        printf("%i \n", example[i]);

    }
}

Why does this give me the error messages: "Excess elemnts in scalar initializer" at "2" in the array I'm defining, and the error message "Subcripted value is not an array, point or vector" at my "[i]" when trying to print out the Ith integer in the array?

Thanks.

4
  • There is a mistake in the initialization: int example = [1,2,3]; and not {} :)
    – Ahmed
    Commented Oct 17, 2015 at 8:51
  • @AhmedEl nope..
    – kzidane
    Commented Oct 17, 2015 at 9:01
  • @JakobH, in C, an array has fixed size — once the size of an array is determined, it cannot be changed. now what is the size that you defined example to be of? how many elements are you trying to push into example?
    – kzidane
    Commented Oct 17, 2015 at 9:02
  • Sorry didn't see the line before main...
    – Ahmed
    Commented Oct 17, 2015 at 9:22

2 Answers 2

1

You have to set the size of the array.

I.E:

int example[10];

then you could do this to set the first element of the array to 1:

example[0] = 1;

You can't do this though:

int example[10];
example = {1, 2, 3};

If you've already defined the array the compiler expects you to define which element (I.E: [0]) of the array you want to define (or change), then what you want to assign to that element (I.E: 1).

if you want the size to be set automatically, you could delete this:

int example[];

and write this:

int example[] = {1, 2, 3};

then the compiler knows that you are defining the array, and setting the values of the values of the 3 elements to 1, 2 and 3.

Your code should look something like this:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int example[] = {1,2,3};

    for (int i = 0; i < sizeof(example) / 4; i++) 
    {
        printf("%d\n", example[i]);
    }
}

Hope this helps! :-)

1

By doing

int example[];

you are initializing a pointer to an array whose size is not defined. After that in

int example = {1,2,3};

yu are adding values to the pointer which is illogical and has no meaning you can just do it like

int example[3];
int example = {1,2,3};

Hope this helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .