1

This is my code initializing the array:

#include <stdio.h>

int main (void) {
    int x, n;

    //            0  1  2  3  4   5   6   7   8   9   10  11  12  13  14  15
    int *array = {2, 4, 6, 9, 11, 13, 15, 17, 19, 21, 25, 29, 30, 34, 35, 38};
    n = sizeof(array) / sizeof(int);

    for (x=0; x<n; x++) {
        printf("%i: %i - ", x, array[x]);
    }

    printf("\nArray's length: %i", n);
    return 0;
}

I'm not understanding why this simple code shows this message:

Runtime error

Thanks in advance.

3 Answers3

1

Change this:int *array = to this: int array[] =. Ideone link: https://ideone.com/ULH7i6 . See this too: How to initialize all members of an array to the same value?

Community
  • 1
  • 1
Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43
1

What did you have in mind when you declared the following line?

int *array = {2, 4, 6, 9, 11, 13, 15, 17, 19, 21, 25, 29, 30, 34, 35, 38};

What comes to mind when I see something like this you're trying to work with an array using pointer arithmetic, which makes for a lot of fun interview questions (and just cool in general :P ). On the other hand you might just be used to being able to create arrays using array literals.

Below is something that talks about the different types of arrays you might be trying to work with. I know you picked an answer but this might be useful to you if you were trying to accomplish something else.

C pointer to array/array of pointers disambiguation

Community
  • 1
  • 1
Daniel Siebert
  • 368
  • 3
  • 12
-2

Your array declaration is not correct.... just edit your declaration to

int *array[] = {2, 4, 6, 9, 11, 13, 15, 17, 19, 21, 25, 29, 30, 34, 35, 38};

here the correction code!

#include <stdio.h>

int main (void) {
int x, n;

//            0  1  2  3  4   5   6   7   8   9   10  11  12  13  14  15
int *array[] = {2, 4, 6, 9, 11, 13, 15, 17, 19, 21, 25, 29, 30, 34, 35, 38};
n =sizeof(array) / sizeof(int);

for (x=0; x<n; x++) {
    printf("%i: %i - ",x,array[x]);
}

printf("\nArray's length: %i", n);
return 0;
}
Peter Petrik
  • 9,701
  • 5
  • 41
  • 65