YehiaMedhat
YehiaMedhat
Why iterating through an array by incrementing pointer gives such output?
This is my code snippet, I was trying to print the elements of the arr by accessing its values from the pointers.
#include <stdio.h>

/**
* main - entry point
* Return: Always sucess (0)
*/

int main(void)
{
/* Declaring vars */
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int i;
int* parr = arr;

/* Try to iterate by pointer incrementation */
for (; *parr != '\0'; parr++)
{
/* output: arr elements plus an unknown element */
printf("%d ", *parr);
}

printf("\n");

/* Try to iterate by index */
for (i = 0; i < 10; i++)
{
/* output: arr elements exactly as they are */
printf("%d ", arr[i]);
}

printf("\n");

/* Try to iterate by both index and pointer */
for (i = 0; i < 10; i++)
{
/* output: arr elements in hexadecimal format */
printf("%p ", *&arr[i]);
}

return (0);
}
#include <stdio.h>

/**
* main - entry point
* Return: Always sucess (0)
*/

int main(void)
{
/* Declaring vars */
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int i;
int* parr = arr;

/* Try to iterate by pointer incrementation */
for (; *parr != '\0'; parr++)
{
/* output: arr elements plus an unknown element */
printf("%d ", *parr);
}

printf("\n");

/* Try to iterate by index */
for (i = 0; i < 10; i++)
{
/* output: arr elements exactly as they are */
printf("%d ", arr[i]);
}

printf("\n");

/* Try to iterate by both index and pointer */
for (i = 0; i < 10; i++)
{
/* output: arr elements in hexadecimal format */
printf("%p ", *&arr[i]);
}

return (0);
}
This is the output; look at the first line of the output, why this 33 showed up?
1 2 3 4 5 6 7 8 9 10 **33**
1 2 3 4 5 6 7 8 9 10
0000000000000001 0000000000000002 0000000000000003 0000000000000004 0000000000000005 0000000000000006 0000000000000007 0000000000000008 0000000000000009 000000000000000A
1 2 3 4 5 6 7 8 9 10 **33**
1 2 3 4 5 6 7 8 9 10
0000000000000001 0000000000000002 0000000000000003 0000000000000004 0000000000000005 0000000000000006 0000000000000007 0000000000000008 0000000000000009 000000000000000A
Thanks in advance 😇
6 replies