(C language) How to write pointers and arrays

How to write pointer assignment

At the time of declaration

char str[10] = "";
char *ptr = str;

When assigning to a pointer later, assign to pointer variable name without *. If you want to substitute the start address of the array, substitute array variable name without &.

char str[10] = "";
char *ptr;

ptr = str;

If you want to assign an address in the middle of the array, add &.

char str[10] = "";
char *ptr;

ptr = &str[5];

Assign to the contents of the pointer

When assigning to the contents of the memory pointed to by the pointer, add *.

char str[10] = "";
char *ptr = str;

*ptr = "t";
ptr++;
*ptr = "e";
ptr++;

Extract the contents of the pointer

To retrieve the contents of the memory pointed to by the pointer, add *.

char str[10] = "text";
char *ptr = str;
char c;

c = *ptr;
ptr++;
c = *ptr;
ptr++;

Recommended Posts