C language | Pointer

Compile and execute a C program on Apple m1:

Farhan Tanvir Utshaw
2 min readApr 7, 2024

gcc

gcc pointer.c -mcpu=apple-m1 -o output.out && ./output.out

g++

g++ pointer.c -mcpu=apple-m1 -o output.out && ./output.out # g++ way

Basic

int var = 5;
int a = 500;
int *pointerToVar ;

pointerToVar = &var ; // reference

printf("var: %d\n", var); // var's content
printf("var: %p\n", pointerToVar); // pointerToVar's content which is an address

printf("var: %d \n", *pointerToVar); // dereference pointerToVar

Function’s getting the address of a variable scoped inside another stack frame


#include <stdio.h>

void foo(int *a)
{
*a = 10;
printf("a content inside foo: %d\n", *a);
}

void foo2(int a)
{
a = 10;
printf("a content inside foo: %d\n", a);
}

int main()
{
int a = 5;

int *pointerToA;

pointerToA = &a; // reference

printf("a content inside main: %d\n", a);

foo(pointerToA);
printf("a content inside main: %d\n", a);

return 0;
}

Pointer arithmetic with 1D array


#include <stdio.h>

void foo(int arr[])
{
for (int i = 0; i < 4; i += 1)
{
arr[i] = 100;
}
}

void printArray(int *arr)
{
for (int i = 0; i < 4; i += 1)
{
printf("%dth index item: %d\n", i, *(arr + i));
}
}

int main()
{
int arr[] = {30, 30, 35, 15};
printArray(arr);
// the name arr refers to the first item's address
printf("3rd index's address: %d\n", &arr[3]); // 3rd index's address

printf("3rd index's content: %d\n", arr[3]);
printf("3rd index's content: %d\n", *(arr + 3));

foo(arr);

for (int i = 0; i < 4; i += 1)
{
printf("%d\n", arr[i]);
}

return 0;
}

Multilevel pointer


#include <stdio.h>

void printArray(int *arr)
{
for (int i = 0; i < 4; i += 1)
{
printf("%dth index item: %d\n", i, *(arr + i));
}
}

int main()
{
int arr[] = {30, 30, 35, 15};
int a = 10;
int *pointerToA = &a;
int **pointerToPointerToA = &pointerToA;
int ***pointerToPointerToPointerToA = &pointerToPointerToA;
int ****pointerToPointerToPointerToPointerToA = &pointerToPointerToPointerToA;

printf("Original: %d\n", a);
printf("De: %d\n", *pointerToA);
printf("De: %d\n", **pointerToPointerToA);
printf("De: %d\n", ***pointerToPointerToPointerToA);
printf("De: %d\n", ****pointerToPointerToPointerToPointerToA);

return 0;
}

Pointer arithmetic with 2D array


#include <stdio.h>

void printArray(int *arr)
{
for (int i = 0; i < 4; i += 1)
{
printf("%dth index item: %d\n", i, *(arr + i));
}
}

int main()
{
int arr[][4] = {
{30, 60, 35, 15}, // pointerToArr + 0
{10, 99, 88, 55}, // pointerToArr + 1
{40, 559, 22, 25} // pointerToArr + 2
};

int **pointerToArr = arr;
for (int row = 0; row < 3; row += 1)
{
// printf("%d\n", arr + row);
for (int col = 0; col < 4; col += 1)
{
printf("%d ", *(*(arr + row) + col));
}
printf("\n");
}

return 0;
}

--

--