C++ Pointers

Array of pointers to ints

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
int* ap[15];
int ai[15] = {};
for (int i = 0; i < 15; ++i) {
ai[i] = i;
ap[i] = &ai[i];
std::cout << *ap[i] << " " << ap[i]<< std::endl;
}
}

Console:

0 0x16d296d14
1 0x16d296d18
2 0x16d296d1c
3 0x16d296d20
4 0x16d296d24
5 0x16d296d28
6 0x16d296d2c
7 0x16d296d30
8 0x16d296d34
9 0x16d296d38
10 0x16d296d3c
11 0x16d296d40
12 0x16d296d44
13 0x16d296d48
14 0x16d296d4c

Pointer to an array of ints

Code:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
int ai[15];
for (int i = 0; i < 15; i++) ai[i] = i;
int (*ptr)[] = &ai;
for (int i = 0; i < 15; i++) {
std::cout << (*ptr)[i] << " ";
}
}

Console

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Notes

  • The parentheses around *ptr are necessary because the [] operator has
    higher precedence than the * operator. Without the parentheses, the
    declaration would be parsed as an array of pointers to int, like int
    *ptr[15].

  • When I took the address of the array, I got a pointer to the first element
    of the array. However, the pointer itself does not contain any information
    about the size of the array.

Pointer to function taking a string argument;

returns an string

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

void replaceX(std::string *str, std::string x)
{
size_t pos = (*str).find("${x}");
if (pos != std::string::npos)
(*str).replace(pos, 4, x);
}

std::string foo(std::string x)
{
std::string str = "hello this is ${x}";
replaceX(&str, x);
return str;
}

int main()
{
std::string (*fp)(std::string) = &foo;
std::cout << (*fp)("foo") << std::endl;
std::cout << (*fp)("bar") << std::endl;
}

Console:

hello this is foo
hello this is bar