Array initialization method using C language pointers. The pointer is actually a number.

It is difficult for beginners to understand how to write the pointer increment, so I will explain it.

#include <stdio.h>

int main(void)
{
    int i;
    unsigned short int num[8];
    unsigned short int *np;
    np = num;

    for(i = 0; i<8; i++){
        *np = 0;
        np++;
    }

    return 0;
}

Since the pointer is not an int, why is it possible to write it as "np ++" to increment it?

Actually, the pointer is also a numerical value. Therefore, it is written as follows. The memory is assigned a continuous serial number (integer value) __ called "address" that represents the __ location. So you can add or subtract. This is the same as char is actually a number, only it is displayed as a character using the character code.

    for(i = 0; i<8; i++){
        *np = 0;
        np++;
    }

bonus

The above code can be abbreviated as below.


    for(i = 0; i<8; i++){
        *np++ = 0;
    }

reference

From the basics again C language 24th Data structure (3) -Basics of pointers Pointers and arrays https://www.grapecity.com/developer/support/powernews/column/clang/024/page02.htm

Part 3 Address and pointer variables http://www.isc.meiji.ac.jp/~re00079/EX2.2011/20110518.html

Recommended Posts