Why this program gives Runtime Error


1
2
3
4
5
6
7
8
9
int main(){     
int *a,*b,*c,*d, e=4;     
int **array[]={&a,&b,&c,&d};     
int i;     
*a=*b=*c=*d=e;     
for(i=0;i<=3;i++)         
printf("%d  ",**array[i]);     
return 0; 
} 
This is how you should write line 5 if you want all the pointers to point to e.

 
a = b = c = d = &e;
Otherwise, if you want to copy the value contained in "e" into the memory areas pointed to by "a", "b", "c" and "d", you need to ensure they point to a memory area you own before dereferencing them:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main()
{
    int* a = new int,
       * b = new int,
       * c = new int,
       * d = new int,
         e = 4;
    int **array[] = { &a, &b, &c, &d };
    *a = *b = *c = *d = e;
    for(int i = 0; i <= 3; ++i) { std::cout << **array[i]; }
    return 0;
}


Output:
4444

Topic archived. No new replies allowed.