Code 1:
#include<stdio.h>
int main(void)
{
int* arr[5];
for(int i=0; i<5; i++) {
arr[i] = (int*)malloc(sizeof(int));
*arr[i] = i;
}
printf("%d",arr[3]);
return 0;
}
Output:
13509232
Code 2:
#include<stdio.h>
int main(void)
{
int* arr[5];
for(int i=0; i<5; i++) {
arr[i] = (int*)malloc(sizeof(int));
*arr[i] = i;
}
printf("%d",arr[3][0]);
return 0;
}
Output:
3
I've declared an array of pointers. Instead of going for *arr[3] to dereference the value stored, I can simply write arr[3][0] to dereference it. It works for all dimensions of arrays. Just by adding an extra zero to it's dimension, dereferences it's value stored at the location.
I couldn't get it, because at the very first place, arr[3] is 1D array and arr[3][0] is 2D array. After all, arr[3] is an address, and arr[3][0] is a value stored at the address arr[3]. Can I use in this way to get rid of * operator? Kindly explain in simple terms.
Thanks in advance.
EDIT 1: Let's take the simplest case, single variable.
#include<stdio.h>
int main(void)
{
int k=5;
int *ptr=&k;
printf("%d",ptr[0]);
return 0;
}
Output:
5