Copy elements of pointer.

I tried to understand pointers and I cant figure out how to copy the elements of the array that the pointer point to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

int main(){

	char a[3] = {'a', 'b', 'c'};

	char p[256];
	char copy[256];
	char *q[256];

	p[0] = *a;
	p[1] = *(a+1);
	q[0] = a;
	
	cout<<p[0]<<endl;
	cout<<p[1]<<endl;
	cout<<q[0]<<endl;

}


so when i print the q[0] it will show abc as the result. is there any way to copy the q[0] element by element into another array. so it will create another copy of array like a[3].
Last edited on
1
2
p[0] = *a;
p[1] = *(a+1);


Should be (or is equivalent to at least):

1
2
p[0] = a[0];
p[1] = a[0];


From there, do you know what a for loop is and how to use it? If not then you should be learning about basic control structures before pointers.

is there any way to copy the q[0] element by element into another array.
You started doing this for the first two elements (you copied 'a' and 'b' into p)
Thanks for the reply. I'm quite familiar with the for loop. I understand that i had copied the first two elements into p, and the q is pointing to the whole array of a. Is it possible to copy into array(like i did to p) from the pointer q?
Yes, it is possible. Pointer to first element of the array can be used just like array:
1
2
3
4
5
6
7
8
9
10
11
int a[10] {0, 1, 2, 3, 4, 5, 6 ,7 ,8 9,};
int a_copy[10];
for(int i = 0; i < 10; ++i) {
    a_copy[i] = a[i];
    a[i] = a[i]*2 + 1;
}
int* p = a;
int p_copy[10];
for(int i = 0; i < 10; ++i) {
    p_copy[i] = p[i];
}
The q is not a pointer! It is an array of pointers. The q[0] is a pointer that points to the first element of array a.
Hi,
Array should be of size 4 at line number 4.

For your que :
"is there any way to copy the q[0] element by element into another array. so it will create another copy of array like a[3]."
Please have a look below sample code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
	char a1[4]= {'a','b','c'};
	char* arr[30];

	arr[0] = a1;

	char a2[4];
	a2[0] = *arr[0];
	a2[1] = *(arr[0]+1);
	a2[2] = *(arr[0]+2);
	a2[3] = '\0';

	cout<<a1<<endl;
	cout<<arr[0]<<endl;
	cout<<a2<<endl;

	getch();
	return 1;
}
Topic archived. No new replies allowed.