Hi i'm new to programming. I wanted to create two integer arrays which are adjacent in memory. i had written the following code, but i'm getting segmentation fault when i run it.
What do you want to do? I mean, *why* do you want them to be adjacent? Most likely, there is a better solution. If not (and please *ONLY* if not): you make one array twice the length you need (int x[6]) and then point to the location you want (int* a1=x; int* a2=x+3;)
#include<iostream>
usingnamespace std;
void printarray(int* a,int size)
{
for(int i=0;i<size;i++)
cout<<a[i]<<endl;
}
int main()
{
int a[3]={0,1,2,}; //the first array
int* pa;
pa = &(a[2]);
pa++;
int* b = pa; //the second array
for(int i=0;i<3;i++)
{
b[i]=i+2;
}
printarray(a,3);
printarray(b,3);
}
You only have one array, the one declared on line 12. pa and b just point to parts of that array.
On line 14 you set pa to point to the last element of array a[], then on line 15 you move it past the end to point to what could be anything (effectively random data). Then you set b to point to this random data.
Then you have your problem code, the for loop at line 19. You have no idea what is in the memory b points to (it could be critical data) but you are attempting to overwrite it. The operating system has detected you trying to write to an area of memory you are not allowed to, and has terminated your program.
To create your two adjacent arrays, I would create one that is double the size you need and use a pointer to point half way using it as the second array
1 2
int a[6] = {0,1,2,3,4,5};
int *b = &a[3];
It's the only way to reliably get adjacent arrays.