2021-06-04 · 2

C Pointers

ctil

This post is over 2 years old. The content may be outdated.

C, C++ pointers


What is a pointer?

A variable made to point to a specific memory location is called a pointer. In other words, you can only use it once you know the address.

Until now, when we declared a variable, we didn't think of that variable being recorded in memory — we just thought of the declared name and value and used them. But actually, declaring int a; is like saying 'use int type, variable name a, in an uninitialized state at memory x132453647 (arbitrary)'. At this point, entering a = 10; is like 'changing the value at memory x132453647 to 10'.

So when we use a pointer, it means 'find memory x132453647 (arbitrary)', not find the variable 'named a'. Once you know the address, naturally you'll be able to know the value too.

Declaring a pointer!

A pointer also looks very similar to how we used to declare variables. Data types like int, float, double, long, char, etc. also exist. Declare it the same as a variable, but just put a * in the middle.

For example

//int-type pointer
int *a;

//float-type pointer
float *a;

//double-type pointer
double *a;

You can declare it as above.

Pointer declaration and initialization — how can we initialize it along with the declaration? Do you remember using the "&" symbol when we learned "scanf"? That "&" symbol is exactly the symbol that tells you the address.

For example

#include <stdio.h>

int main() {
    int num1 = 5;
    int num2 = 10;
    int *num1Ptr = &num1;
    int *num2Ptr = &num2;

    printf("%d %d\n", num1, *num1Ptr);
    printf("%d %d\n", num1, num1Ptr);
}

/*
Output: 5  5
      10 10
*/

You can do it as above. To explain a bit: after declaring int-type variables num1, num2, we also declare int-type pointers num1Ptr, num2Ptr, and

int* num1Pointer = &num1;

int * num1Pointer = &num2;

entering these, you can confirm they each receive the addresses of num1 and num2. As a result, you can confirm that the num1 value and the value of *num1Ptr are printed identically.

Caution!

When you declare an int-type pointer int* p, and do p = &num1 — assigning the num1 variable's value into the int-type pointer variable p —

using p with a * attached, like printf("%d", *p), represents the value at the address p points to, and

using just p, like printf("%d", p), represents the address p is pointing to.


Original (Korean): tistory — published 2021-06-04, migrated to this blog. This translation was generated with the help of AI.

Comments

Delete this comment?

Related posts

C Pointers · 나봄하랑