Recently, while writing Golang for part-time jobs and hobbies, and writing C language for school lectures and assignments, I thought that pointers are difficult to understand, and when I talk about that story with various engineer students, it is difficult for everyone to understand. I thought, so this time I tried to summarize the pointers in C language (Golang was made with reference to C language)! !! !!
A computer reserves a variable in a program in memory and stores an address to identify its location. Pointers are used when the program wants to handle the address. In other words, a pointer is a variable that handles an address.
Let's look at the syntax for using pointers in C.
`Data type * pointer variable name;`
(Example) Declare a pointer to an int type variable
int *p;
--You can get the address by adding "&" to the variable.
&Variable name
(Example)
#include<stdio.h>
int main() {
int x = 1;
int *p;
p = &x;
printf("「&x "address: %p\n", &x);
printf("Address indicated by "p": %p\n", p)
return 0
}
(Execution result)
「&x "address: 00A2EE76
Address indicated by "p": 00A2EE76
--If you add "*" to the pointer, you can get the value in the address indicated by the pointer.
*Pointer variable name;
(Example)
#include<stdio.h>
int main(){
int x = 1;
int *p = &x;
printf("Value in the address indicated by "p": %d\n", *p);
return 0;
}
(Execution result)
The value of the address indicated by "p": 1
What I think is confusing and needs attention is how to interpret "". When assigning an address when declaring a pointer, it is "int * p = & x", so it looks as if "& x" is assigned to " p", but it is semantically "p = & x". It becomes. In other words, the following two are synonymous.
int x = 1;
int *p;
p = &x;
int x = 1;
int *p = &x;
The second point to note is about initialization. Just by declaring a pointer variable, the address indicated by that pointer variable becomes indefinite. Therefore, if you use the pointer variable without initializing it, you will access an unspecified address, which causes a bug.
#include<stdio.h>
int main() {
int x = 1;
int *p;
//The following line causes a bug because p has not been initialized
*p = x;
}
You can work with arrays using pointer operations by assigning the start address of the array to a pointer variable. As you can see in the sample below, & num [0]
and num
are the same.
Also, * (p + i)
and num [i]
are the same.
#include<stdio.h>
int main() {
int *p;
int i;
int num[3] = {1, 5, 10};
//The following line assigns the start address of the array to the pointer variable
p = num;
for(i = 0; i < 3; i++) {
printf("%d\n", *(p + i)); //Advance the pointer by the number of elements to take the value
}
return 0;
}
(Execution result)
1
5
10
This time, I have summarized the basic points that are easy to misunderstand about pointers in C language. Next time, I'll summarize some of the misleading points about Golang pointers. !! !! !!
Recommended Posts