I am trying to learn how to use pointers in C and have come across the following code but am not sure what it means.
float xLeft [4] , *pLeft = xLeft ;
I know that xLeft[4] creates a an array of length 4, but I'm not sure what the second part *pLeft = xLeft does?
NB - the original question copied an incorrect version of the asterisk symbol ∗ from a textbook. The code in the question has now been edited.
CodePudding user response:
∗ (Unicode U 2217, the “asterisk operator”) is not a correct character for C source code. If it is corrected to an asterisk, then float xLeft [4], *pLeft = xLeft ; first declares xLeft to be an array of 4 float, then declares pLeft to be a pointer to float and initializes it using xLeft.
When an array is used in an expression other than as the operand of sizeof, the operand of unary &, or as a string literal used to initialize an array, it is automatically converted to a pointer to its first element. So float … *pLeft = xLeft ; initializes pLeft to point to the first element of xLeft.
CodePudding user response:
Think of it this way,
float xLeft [4];
float *pLeft=xLeft;
say
xLeft[0]=1;
xLeft[1]=2;
xLeft[2]=3;
xLeft[3]=4;
Each memory location we will have a address and this address holds a value.
Let's assume our float array xLeft is located at address 0x0001. By that we mean the first element of xLeft, which is xLeft[0], has the address 0x0001 and a value 1. Similarly xLeft[1] has the address 0x0002 and a value 2, and so on, for the other elements of the array.
*pLeft is a pointer of type float, and when we assign *pLeft=xLeft, we just want our pointer to point or hold the address of xLeft. In our example *pLeft will be pointing to 0x0001.
If you try:
printf("The value of pLeft is: %f\n", *pLeft);
You should get the value at 0x0001 which is 1 in our case. With:
printf("The value of pLeft is: %p\n", pLeft);
Should return you the address 0x0001.
