Hi how to access character array using integer point.
char arr[10] = {'1','2','3','4','5','6','7','8','9','10'};
int *ptr;
How i can print values of 'arr' using pointer ptr?
Hi how to access character array using integer point.
char arr[10] = {'1','2','3','4','5','6','7','8','9','10'};
int *ptr;
How i can print values of 'arr' using pointer ptr?
It is a little unclear what your goal is, but trying to print out a character array with an integer pointer is a bit like trying to get to the second step taking four-steps at a time. When you tell the compiler that you would like to reference a memory address with an integer pointer, the compiler knows that an integer is sizeof (int)
bytes (generally 4-bytes on x86/x86_64). So attempting to access each element in a character array with an integer pointer and normal pointer arithmetic wouldn't work. (you would be advancing 4-bytes at a time).
However printing the character array though an integer
pointer is possible if you use the integer pointer for the starting address of the array and advance the pointer by the number of characters in the array by casting back to char
. While it is doubtful this is your goal, the plain statement of your question seems to suggest it. To accomplish this, you could:
#include <stdio.h>
int main (void)
{
char arr[] = {'1','2','3','4','5','6','7','8','9'};
int *ptr = (int *)arr;
unsigned int i;
for (i = 0; i < sizeof arr; i++)
printf (" %c", (*(char *)ptr + i));
putchar ('\n');
return 0;
}
Output
$ ./bin/char_array_int_ptr
1 2 3 4 5 6 7 8 9
Note: your original initialization of your array with a character '10'
was invalid. If this was an assignment, it is likely intended to expose you to how pointer arithmetic is influenced by type and the ability to cast from and to type char
(without violating strict aliasing rules)
If you are just after the integer values you can print out the characters as integers
for (i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i)
{
printf( "%d ", arr[i] );
}
Using a pointer of the wrong data type to access anything is undefined behavior, thus making it not something you want to do. If you want to cast a char to an integer, you can do that. If you want to print the integer value of a char, you can do that too.
But using a pointer type integer to access a char array is undefined behavior.