Skip to content

Pointers and Arrays

Derek Snider edited this page May 19, 2026 · 1 revision

Pointers & Arrays

Pointers

C-style pointers work as expected:

int x = 42;
int *p = &x;
cout << *p << endl;       // 42
*p = 100;
cout << x << endl;        // 100

Pointer types

char *s = "hello";
int *ip;
void *vp;
char **argv;              // pointer to pointer

Struct pointers and ->

struct Point { int x; int y; };

Point p = { 10, 20 };
Point *ptr = &p;
cout << ptr->x << endl;     // 10

// chained access
// a->b->c, a->b.c, a.b.c all work

Fixed-size arrays

int nums[5] = { 10, 20, 30, 40, 50 };
cout << nums[0] << endl;    // 10
cout << nums[4] << endl;    // 50

char buf[256];
sprintf(buf, "hello %s", "world");
puts(buf);

Char arrays and string literals

char name[32] = "Alice";
char greeting[] = "Hello";    // size inferred from literal

Multi-dimensional arrays

int grid[3][3];
grid[0][0] = 1;
grid[1][1] = 5;

Subscript operator

Works on arrays, pointers, strings, and containers:

int arr[3] = { 10, 20, 30 };
cout << arr[1] << endl;       // 20

char *s = "hello";
cout << s[0] << endl;         // h

// also works with map
map<string, int> ages;
ages["Alice"] = 30;
cout << ages["Alice"] << endl;

argv

int main(int argc, char **argv) {
    for (int i = 0; i < argc; i++)
        puts(argv[i]);
    return 0;
}

argv[i] reads the i-th char * directly via raw-pointer subscripting.

What's next?

Clone this wiki locally