0

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;

        }}
Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
  • 1
    The condition in the for loop in ptr_multiply is incorrect. – lil_noob Apr 29 '20 at 08:06
  • Due to the arcane and obsolete rules of C parameter adjustment, and its misleading grammar, `a1` *is already a pointer.* You can increment it and use it like you use `ptr`. `a1`, as opposed to `ptr`, has the advantage of actually pointing to something ;-). – Peter - Reinstate Monica Apr 29 '20 at 08:06
  • You also want to finish each output with `<< std::endl` in order to see it (because the output buffer is flushed) in case the program crashes later. In your program there is possibly some buffered output you program has made which never reached the console. – Peter - Reinstate Monica Apr 29 '20 at 08:10

1 Answers1

2
*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?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185