In this code, I don't understand why the input character value is being put into (ptr + i) but then we print out ptr[i]. I know they are different because I am printing out the values in the first for loop, but I don't understand what the difference between them is and why we are using one to accept input with scanf and a different one to output.
#include<stdio.h>
#include<stdlib.h>
int main ()
{
int n, i;
char *ptr;
printf ("Enter number of characters to store: ");
scanf ("%d", &n);
ptr = (char *) malloc (n * sizeof (char));
printf("POINTER %p\n", ptr);
for (i = 0; i < n; i++)
{
printf ("Enter ptr[%d] (%p) (%p): ", i, ptr[i], ptr + i);
/* notice the space preceding %c is
necessary to read all whitespace in the input buffer
*/
scanf (" %c", ptr + i);
}
printf ("\nPrinting elements of 1-D array: \n\n");
for (i = 0; i < n; i++)
{
printf ("%c ", ptr[i]);
}
//signal to operating system program ran fine
return 0;
}
In addition, I know doing ptr + i = ptr + (i * numberofbytes) based on the number of bytes of the data type of pointer, so it makes sense that we would store each new input into a memory address with that number of bytes that we used malloc for. But then why do we print out ptr[i] instead of ptr + i?
Hope this is described specifically enough, let me know if it isn't.
Thank you!
Due to the pointer arithmetic the expression
ptr + ihas the typechar *and points to the i-th elemenet of the array. The functionscanfexpects a pointer to an object to which the entered data will be stored.The expression
ptr[i]that is the same as*( ptr + i )yields the object pointed to by the expressionptr + i.From the C Standard (6.5.2.1 Array subscripting)
So the expression
ptr + ipoints to the i-th object. And the expression*( ptr + i )that is the same asptr[i]yields the object itself pointed to by the expressionptr + i.