Brittany May
Brittany May

Reputation: 21

Misuse of a pointer is producing a segmentation fault. I'm still not sure how to correct it though

After doing some reading, I feel like I understand what is going wrong here, but I am not sure how to fix it. As far as I understand, the issue is with how I wrote the input of an array in line 4 (emphasized). The issue itself is that when I run the code the first time in any IDE it works fine, but then when I try to play around with the numbers, it treats the new array as if it shares a size with the first one, even when it doesn't. It seems like I should be rewriting line 4 in some alternate way so as not to abuse the pointer, but I'm not sure how.

using namespace std;

void INSERTIONSORT(int* A) { //THIS IS LINE 4
    int i;
    int key;
    for (int j = 0; j < sizeof(A); j++) {
        key = A[j];
        i = j - 1;
        while (i >= 0 && A[i] > key) {
            A[i + 1] = A[i];
            i = i - 1;
        }
        A[i + 1] = key;
    }
}

void display(int* A) {
    for (int i = 0; i <= sizeof(A)-1; i++)
        cout << A[i] << " ";
    cout << endl;
}

int main() {
    int myArray[] = { 2,1,4,3 };
    cout << "Array before Sorting: ";
    display(myArray);
    INSERTIONSORT(myArray);
    cout << "Array after Sorting: ";
    display(myArray);
    return 0;
}```

Upvotes: 1

Views: 58

Answers (1)

lenik
lenik

Reputation: 23536

This line is the problem:

for (int j = 0; j < sizeof(A); j++) {

what you need is the size of your array (the number of elements), what you get is the size of your pointer in bytes (=4, for 32-bit systems), generally you want to explicitly pass the array size or use some kind of container (std::vector) that knows its own size.

Upvotes: 1

Related Questions