Home > Back-end >  I'm getting a segmentation fault (core dumped) when I try to initialize a 1d array of 100 eleme
I'm getting a segmentation fault (core dumped) when I try to initialize a 1d array of 100 eleme

Time:10-05

int main(void) {

  int x[100];
  int *myPtr;
  int j;
  myPtr = &(x[100]);

  for (j=0; j<100; j  ) {
    *myPtr = j;
    myPtr   ;
  }

  printf("%d", *myPtr);

  return 0;
}

this is my code (so far)^ these are my directions:

  1. Create a 1-dimensional integer array of size 100. a. Using a pointer load the array with consecutive numbers from 0 to 99. b. Using a pointer write out the array in ascending order. c. Using a pointer write out the array in descending order.

CodePudding user response:

The assignment in myPtr = &(x[100]); is incorrect: you make myPtr point to the end of the array, causing undefined behavior when you write there and beyond.

Change the assignment to myPtr = x; or myPtr = &x[0]; and change the last statement to printf("%d", *x);

Here is a modified version:

#include <stdio.h>

int main(void) {
    int x[100];
    int *myPtr;
    int j;

    myPtr = x;

    for (j = 0; j < 100; j  ) {
        *myPtr = j;
        myPtr  ;
    }

    printf("x contains numbers from %d to %d\n", x[0], x[99]);

    return 0;
}

CodePudding user response:

Fetching x[100] is undefined behavior.

myPtr = x;
for (j=0; j<100; j  )
  *myPtr   = j;

To get the address of an array it's enough to evaluate x, which is the same as &x, the same as &x[0], the same as &0[x], the same as &*(x 0).

CodePudding user response:

x[100] is a nonexistent element of the array x because the valid range of indices is [0, 100).

So this statement

myPtr = &(x[100]);

sets the pointer myPtr to the address of the memory after the last element of the array. Dereferencing such a pointer invokes undefined behavior.

In the for loop that fills elements of the array you need a pointer that will pointer to the first element of the array x.

You can write

myPtr = &x[0];

Though it is simpler to write

myPtr = x;

because the array designator x used as an initializer is implicitly converted to a pointer to its first element.

Your program can look the following way

#include <stdio.h>

int main(void) 
{
    enum { N = 100 };
    int x[N];
  
    int value = 0;
    
    //  fill the array
    for ( int *myPtr = x; myPtr != x   N;   myPtr )
    {
        *myPtr = value  ;
    }
    
    //  output the array in the ascending order
    for ( const int *myPtr = x; myPtr != x   N;   myPtr )
    {
        printf( "%d ", *myPtr );
    }
    putchar( '\n' );
    
    //  print the array in the descending order
    for ( const int *myPtr = x   N; myPtr != x;  )
    {
        printf( "%d ", *--myPtr );
    }
    putchar( '\n' );
    
    return 0;
}

In the last two for loops there is used a pointer of the type const int * because within the loops elements of the array pointed to by the pointer are not being changed.

  • Related