+ 2
How to print value from array using pointer to array
Refer code below: https://code.sololearn.com/cA106A12a114 How can I print value 12 using variable p1?
14 Respostas
+ 3
*( p1[ 0 ] + 1 ) prints 12.
Not sure what you're doing at line 15 though.
+ 3
In your program, you are successfully able to print values of an array via a pointer pointing to it.
What's the issue then ?
+ 3
Arsenic
Thank you so much! 🙏
I think I'd rather not use the (*ptr) way, it's rather confusing (for me at least).
+ 3
Hey Ipang hope it will help you
&-this gives address of variable
* This is value at that address ( in pointers)
*(p1[0]+1) means
p1[0]=p1=base address of array
p1[0]+1= it means pointer now pointing to next element of array
*(p1[0]+1)=it means array next element value
+ 2
No, we can't
By doing
int (*ptr)[2] = &arr;
We are declaring a single pointer which is meant to point at a data type of " int (*)[2] " which is an integer array of size 2 and making it point to the array "arr" which has to be of size 2 otherwise program will generate error.
Comparing it with
int *ptr = &arr;
Here the pointer "ptr" in meant to point to any integer value, and is currently pointing to first element of the array "arr" . The difference here is that, here unlike the other case, size of "arr" doesn't matter to pointer.
As of "p1[1]" is considered then this is the case of pointer arithmetic where "ptr[n]"
can be represented as (ptr + n*sizeof(data type it is pointing to) ) which means trying to acess p1[1] will lead to undefined behaviour.
+ 2
Ipang it can be very useful, especially in case of using 2-D arrays where *(ptr[x] + y) can be used to access (x,y) element of the matrix.
+ 1
Thank you... Creating a pointer which should point to array
+ 1
So we store address of <arr> into <p1>. I suppose it is saved in index 0.
How do I save address of another array into <p1> at index 1?
+ 1
Ipang , can we ? If yes , plz help me understand...
My current understanding is that P1 is just a pointer which has only one place holder which point to the arr of type int [2]
In other words , if arr[3] is there , it should have been int (*P1)[3]
0
No problem 👌
How do we assign an address for <p1>[1]?
0
Is it not same way what you suggested?
(p1[0] + 1)
0
I thought you mean to say that <p1> is a pointer that stores address of arrays (e.g. address of 2 array) 🙄
0
Hi Martin Taylor , does both p and p1 same ? If none of them is correct, could you please give propper example ?