Understanding Pointers and Structures in C++

Pointers

A pointer is a variable that stores the memory address of another variable. For example:

int *p;

Here, p holds the address of an integer value.

An array name acts as a constant pointer to the first element of the array.

When reading declarations from left to right:

  • const int *p declares a pointer to a constant integer. The value pointed to cannot be modified via p.
  • int *const p declares a constant pointer to an integer. The address stored in p cannot be changed.

Function Parameter Passing

In C++, parameters can be passed by value, pointer, or reference:

Pass by Value

Changes to the parameter inside the function do not affect the original argument:

#include <iostream>
using namespace std;

void modifyValue(int val) {
    val = 100;
}

int main() {
    int num = 1;
    modifyValue(num);
    cout << num << endl; // Outputs: 1
    return 0;
}

Pass by Pointer

Passing addresses allows functions to modify the original variables:

#include <iostream>
using namespace std;

void modifyViaPointer(int* ptr) {
    *ptr = 100;
}

int main() {
    int num = 1;
    modifyViaPointer(&num);
    cout << num << endl; // Outputs: 100
    return 0;
}

Pass by Reference

References provide an alias to the original variable:

#include <iostream>
using namespace std;

void modifyViaReference(int& ref) {
    ref = 100;
}

int main() {
    int num = 1;
    modifyViaReference(num);
    cout << num << endl; // Outputs: 100
    return 0;
}

Multiple Indirection

Pointers can point to other pointers:

short int **ppi;

This declares ppi as a pointer to a pointer of type short int.

Function Pointers and Pointer Functions

Function Pointers

These store addresses of functions:

int func(char, double);          // Regular function declaration
int (*pFunc)(char, double);      // Pointer to such a function

Pointer Functions

Functions that return pointer values:

int* getPointer(int x, int y);

Structures

Structures group related data items:

struct Student {
    char id[8];
    char name[8];
    char gender[4];
    int age;
};

To simplify usage, typedef can create aliases:

typedef struct Student {
    char id[8];
    char name[8];
    char gender[4];
    int age;
} student_t;

Variables, pointers, and arrays of structurse can then be declared:

student_t student1 = {"ID001", "Alice", "Female", 20};
student_t *ptr_student = &student1;
student_t students[3] = {
    {"ID002", "Bob", "Male", 22},
    {"ID003", "Charlie", "Male", 21},
    {"ID004", "David", "Male", 23}
};

Enumerations

Enums define named integer constants:

enum GPIO_Mode {
    GPIO_Mode_AIN = 0x0,
    GPIO_Mode_IN_FLOATING = 0x04,
    GPIO_Mode_IPD = 0x28
};

They help constrain variable values to predefined sets.

Tags: C++ pointers Structures function parameters References

Posted on Tue, 18 Aug 2026 16:39:12 +0000 by mgs019