-3

I'm trying to pass a 2D array to a function using pointers. The function is going to initialise the array.

I get a segmentation fault: 11 at run time

The code is as follows

typedef struct {
    char name[100];
    int runs;
    int batstatus;
    float overs;
    int bruns;
    int wickets;
}player;

player selectbowler(player *team) {
    srand((unsigned) time(null));
    int d = rand()%10;
    if(team[d].overs < 4) {
        player p = team[d];
        return p;
    }
    else {
        return selectbowler(team);
    }
}

void updatebowlwickets(player *team[], player bowler) {
    for (int i = 0; i < 10; i++)
    {
        //Segmentation fault was being generated over here.
        if( strcmp(team[i]->name, bowler.name) == 0) {
            team[i]->wickets += 1;
        }
    }
}
//made a call to the above method via
player teams[2][10];
//Code part goes here
player bowler = selectbowler(teams[0]);
updatebowlwickets((player **)teams[0], bowler); 

I'm sorry for uploading a wrong code earlier.

Besides can you please let me know when there would be a segmentation fault: 11, I already know that a segmentation fault would be generated she we try to access an invalid address or when we run out of the memory space allocated in the hardware by the OS. Please let me know if there are any other reasons or even if the stated reasons are wrong.

Thanks!

iMinion
  • 11
  • 3

2 Answers2

1

Theres a few things going on here.

You say that a segment fault is generated when accessing an invalid address. That's true. Usually, it's when memory has not been allocated or you are trying to access memory that doesn't exist, such as the 8th element in a 7th element array. That's similar to what is happening here.

Here's the syntax for accessing a multi-dimensional array in C:

    multi[row][col]
or
    *(*(multi + row) + col)

In your code, you are accessing your elements as follows:

    *((overs+i*7) + j) = -2;
and
    *((overs+i*7) + 6) = 0;

One error is that you multiply each row by 7, which refers the compiler to memory outside of your array. For example, when i=20, you are trying to access overs[140] instead of overs[20].

Secondly, you are only initializing your columns up until the 6th column. In your second for loop with "j" as your counter, your upper limit is 6 when it should be 7. This won't directly cause a segmentation fault. The uninitialized elements will contain garbage/random values in memory.

0

Concise answer:

You are accessing your array elements as:

  *((overs+i*7) + j)

Which is:

  *((array + column * height) + row)

This is a little wrong and leads you to go out of bounds (Multi dimensional arrays are laid out row by row). The correct way is:

  *((array + row * width) + column)

Which in your case is:

  *((overs + j*20) + i)

Of course you can always just do:

  overs [i][j]

And forget the pointer approach (it evaluates to the same)

Baldrickk
  • 4,291
  • 1
  • 15
  • 27