Pointer vs Array Name
C
Hard
3 views
Problem Description
Show the difference between an array and a pointer. The sizeof() operator, the increment operation, and assignment. Which operation is valid where?
Official Solution
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50}; // array
int *ptr = arr; // pointer to first element
printf("Array vs Pointer Demonstrationnn");
/* sizeof operator */
printf("sizeof(arr) = %zu bytesn", sizeof(arr)); // total size of array (5 * sizeof(int))
printf("sizeof(ptr) = %zu bytesn", sizeof(ptr)); // size of pointer (usually 4 or 8 bytes)
printf("sizeof(*ptr) = %zu bytesn", sizeof(*ptr));// size of the element pointed by ptr
printf("n");
/* Accessing elements */
printf("arr[0] = %d, *ptr = %dn", arr[0], *ptr);
/* Increment operation */
// arr++; // ❌ ERROR: cannot increment array name
ptr++; // ✅ pointer can be incremented
printf("After ptr++, *ptr = %dn", *ptr);
/* Assignment operation */
// arr = ptr; // ❌ ERROR: cannot assign to array name
int *p2;
p2 = ptr; // ✅ pointer can be assigned
printf("After p2 = ptr, *p2 = %dn", *p2);
/* Reset pointer to start of array */
ptr = arr;
printf("nTraversing array using pointer:n");
for (int i = 0; i < 5; i++)
printf("%d ", *(ptr + i));
printf("n");
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!