-4
#include<iostream>
using namespace std;
int main()
{
    int a,count=0;
    cin>>a;
    int* arr;
    while(a)
    {
    int x= a%10;
    a=a/10;
    *(arr+count)=x;
    count++;
    }
    for(int i=0 ;i< count-1; i++)
    {
        cout<<*(arr+i);
    }
}
/* o/p :segementation error
// i/o :5*/

** array with pointers

why segmentation error

partitioning int in int array **

segmentation error

msc
  • 33,420
  • 29
  • 119
  • 214

2 Answers2

3

Accessing an uninitialized value has undefined behaviour (there are exceptions, but none that apply to your case).

arr is uninitialized:

int* arr;

The value of arr is used here:

*(arr+count)=x;

Therefore the behaviour of your program is undefined.

eerorika
  • 232,697
  • 12
  • 197
  • 326
-1
#include<stdio.h>
int main()
{
    int a,count=0;
    int i;
    scanf("%d",&a);
    int* arr=&i;
    while(a)
    {
    int x= a%10;
    a=a/10;
    *(arr+count)=x;
    count++;
    }
    for(int i=0 ;i< count; i++)
    {
        printf("%d",*(arr+i));
    }
    return 0;
}

**YES we can create dynamic array also like this may be not a good practice but really helpful to save memory **

  • `int i;` is a single integer. It is not an array. `*(arr+count)=x;` has undefined behaviour for all other values than `count == 0`. – eerorika Nov 06 '17 at 15:47
  • @user2079303 above program works fine... i just want to collect separate integers from 'a' . no undefined behavious seems to be present also...... *(arr+count) is just getting contagious memory – shubhs_001 Nov 06 '17 at 16:10
  • the program may *appear* to "work fine", but that's just because you were unlucky. Just because the program "works" doesn't mean that the behaviour isn't undefined. There is no guarantee that your program would continue working if you change compilation options, swap the compiler, run on different cpu, or use different input ... – eerorika Nov 06 '17 at 19:27
  • `*(arr+count)` is "just" getting *contiguous* memory **that you never allocated and therefore may be clobbered by other parts of your program ... or you may be clobbering the the memory that was used for something else**. If you "want to collect separate integers from 'a'", then what you need is an array (or some other data structure that represents a collection). – eerorika Nov 06 '17 at 19:34