A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location.
(a) Define a pointer variable: int *ptr;
(b) Assign the address of a variable to a pointer: ptr = &var;
(c) Access the value at the address available in the pointer variable: int value = *ptr
For 32-Bit Word system (e.g. MCU)
32-CPU: 1 word = 4 bytes (32bit)
Memory: byte units
Int : 4 byte
Pointer variable: 4 byte (default)
Example Code
#include<stdio.h>#include<stdlib.h>intmain() {int var =20; doublea[4] = { 2,2,3,4 };// Pointer Declarationint*ptr;double*ptr2 =NULL;// good practice for not Addr. assgined pointerdouble*ptr3 =NULL;// Pointer Assignmentptr =&var;// store address of var in pointer variableptr2 = a;ptr3 =&a[0];printf("Address of var: %x\n",&var);printf("Address of a : %x\n",&a);printf("Address of a[0]: %x\n",&a[0]);// Using Pointer - Access the values pointed by Ptrprintf("\nAddress stored in \n ptr: %x \n ptr2: %x \n ptr3: %x\n", ptr, ptr2, ptr3);printf("Value of \n *ptr: %d \n *ptr2: %.1f \n *ptr3: %.1f\n",*ptr,*ptr2,*ptr3);system("pause");return0;}
#include<stdio.h>intmain(){int*numPtr;int num1 =10;int num2 =20; ① ________________printf("%d\n",*numPtr); ②_________________printf("%d\n",*numPtr);return0;}
실행 결과
10
20
Solution
① numPtr =&num1;② numPtr =&num2;
Exercise 2
int x =10; double y=2.5;int*ptrX =&x; int*ptrY =&y;/*-Print the address of variable ‘x’-Print the address of variable ‘y’-Print the value of pointer ‘ptrX ‘-Print the address of pointer ‘ptrX ‘-Print the size of pointer ‘ptrX ‘*//*-Print the value of pointer ‘ptrY ‘-Print the address of pointer ‘ptrY ‘-Print the size of pointer ‘ptrY */
Exercise 3 - for EC only
int x =10; double y=2.5;int*ptrX =&x; int*ptrY =&y;// Typecast pointer 'ptrY' to as (double *)