Awais Sajid
Awais Sajid

Reputation: 1

segmentation fault in pointers while handling arrays

I am trying to multiply array elements with 5 but I am getting the error of core dumped and if not, then, it only multiplies 5 with first element.

Here the code:

    #include <iostream>
    using namespace std;

    int ptr_multiply(int[],int);
    int main(){

        int size;

        cout<<"Enter the size of an array ==";
        cin>>size;

        int arr[size];


        cout<<"Enter the elements of array ==";

        for (int i=0;i<size;i++){

        cin>>arr[i];
        }

        ptr_multiply(arr,size);

        }

    int ptr_multiply(int a1[],int s1){

        int *ptr;   


        for (int i=0;s1;i++)
        {

            *ptr=a1[i];

            ptr*=5;

            cout<<"The Elements"<<" "<< i <<" "<<" after multiplying 5 is =="<<*ptr;

        }}

Upvotes: 0

Views: 41

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123440

*ptr=a1[i];
ptr*=5;

First line: You dereference a pointer that points nowhere (it is uninitialized). That is wrong and causes undefined behavior. You try to assign to an int when there is no int.

Second line: You do not dereference the pointer. You multiply the value of the pointer by 5 when you actually want to multiply the int it points to by 5 (remember: there is no int it points to).

You do not need a pointer here:

for (int i=0;i < s1;i++) {
    int value = a1[i];
    value *= 5;
    cout<<"The Elements"<<" "<< i <<" "<<" after multiplying 5 is =="<<value;
}

Also the condition was wrong. It should be i < s1.

Last but not least, dont use C-arrays in C++. They are difficult to use and error-prone. Prefer std::array for fixed size arrays and std::vector for dynamic size. Actually int arr[size]; is not standard C++, see Why aren't variable-length arrays part of the C++ standard?

Upvotes: 2

Related Questions