C指针Pointers

C语言从初中就开始接触了,当时感觉劝退的东西就是指针了,这篇对指针进行一个整理和记录。之所以用英语是因为权威教材和指南(还有C语言本身)都是来自英文世界,用英文理解这些东西可以很大程度地减少误解,有利于直观理解。

1. Pointer for a variable

Pointers, which are the addresses of variables.

For example in this code snippet:

int a = 54;

54 is the value of the variable, in other words, it is the value that is stored in the location reserved for the variable called 'a'. Now, let's ask ourselves, where is a? The location of 'a' can be found using a pointer!

int a = 54;
std::cout<< &a<<"\n"; //This will print the LOCATION of 'a'
// we use & to get the address.

A basic and important example of code

char c='S';
//We declare a pointer to char, for that we use the *
char *p;
//Assign address of the char c, to pointer p. To get the address of a variable we use &
p=&c;
printf ("\n This is the value of char c: %c ", c);
//As we said, we use & to get the address. We are printing the memory address in which c is located:
printf ("\n This is the address of char c: %d ", &c);
printf ("\n This is the address that pointer p is pointing at, which is the address of c: %d ", p);
//we use * to get the content in the address we are pointing at
printf ("\n This is the content of the address that pointer p is pointing at, which is the value of c: %c ", *p);
printf ("\n This is the address of the pointer (a pointer has to be located somewhere as well as any variable): %d ", &p);

2. Pointer for an array

2.1 Int Array

When you need to store a list of integers, you could use a buffer of memory to do it, which is just a chunk of empty memory that can be filled with the integers you need. For example, suppose we need to store a list of 5 integers and print the whole list. We could do something like the following:

#include <stdio.h>
int main()
{
    int arr[5];
    arr[0]=11;
    arr[1]=12;
    arr[2]=13;
    arr[3]=14;
    arr[4]=15;
    for(int i=0;i<5;i++)
    {
        printf("\n Array value at position %i: %i \n",i, arr[i]);
    }
}

In the line 'int arr[5];' we are declaring an array of 5 integers. So the program allocated a buffer of 20 bytes because each integer takes 4 bytes. Then we assign an arbitrary integer to each of the positions, and then we print them on a loop.

However, what if we want to print arr[5]? You might be thinking that line would cause an error because we don’t even have a seventh position in our array. However, it will not be in C! (In python, it would cause an error.)

Here is the output sample:

Array value at position 0: 11
Array value at position 1: 12
Array value at position 2: 13
Array value at position 3: 14
Array value at position 4: 15
Array value at position 5: 3354901908 //not error, but output something strange

Because Our array is actually only 5 positions in size (for 0 to 4th). It is merely a chunk of memory. In this case, our variable 'arr' is just a pointer to the first byte of that chunk of memory. When we do, for example, arr[2], we are pointing to the first byte of the chunk of memory plus 8 bytes, because each integer has 4 bytes, so we move in memory to point to the place in which is stored the third position.

When we do arr[5], it comes to an unassigned position, so we get a random or unexpected value ‘3354901908’. So C allocates the memory needed to place a buffer but does not have any control that prevents you from accessing the wrong place.

2.2 Character Array

Now, we can use pointers to point to the first character of an array of characters, and move through it.

char *p2 ;
//We use malloc to allocate 6 bytes
p2 = malloc(6);
printf ("\n This is the address that pointer p2 is pointing at %d ", p2);
//p2 is an address as well as a variable, so it also has its address
printf ("\n This is the address of p2: %d ", &p2);
//Now we assign values to the bytes we have allocated:
*(p2+0)='h';
*(p2+1)='e';
*(p2+2)='l';
*(p2+3)='l';
*(p2+4)='o';
*(p2+5)=0;
printf("\n This is p2 printed as a string: %s ",p2);

0 (the ASCII for NULL), is the end of the string. SO if we put a 0 in the middle of our char array:

*(p2+2)=0;
printf("\n This is the string we just created: %s ",p2);
//It prints only "he"

a string can be created in a shorter way, for instance:

char *p3=&"hello";
printf("\n This is the content pointed by p3: %s ", p3);

As we said, pointer also has its address. Now, let's make a pointer to pointer to char, we will use the pointer p that points to the char c we declare previously.

char **pp;
pp=&p;

So, imagine pp is a box (the first box), that contains an address that points to a second box, that contains an address that points to a third box, that contains a char.

printf("\n This is the address in which pp is allocated, the address of the first box: %d ", &pp);
printf("\n This is the address  pp points at, the content of the first box: %d ", pp);
printf("\n This is the content of the second box: %d ", *pp);
printf("\n This is the content of the third box: %c ", **pp);

Because PP also has its address, so we can create as many pointers to pointers as we need.

char ***ppp;
ppp=&pp;
printf("\n This is the content of ***ppp: %c ", ***ppp);

Using a pointers to pointers can be very useful. For example:

If you want to have a list of characters (a word), you can use char *word

If you want a list of words (a sentence), you can use char **sentence

If you want a list of sentences (a monologue), you can use char ***monologue

If you want a list of monologues (a biography), you can use char ****biography

If you want a list of biographies (a bio-library), you can use char *****biolibrary

//Let's see how we could implement a list of words
char **pp2=malloc(100);
//pp is the first address
*pp2=&"hello";
*(pp2+1)=&"world";
printf("\n This is hello: %s ", *pp2);
printf("\n This is world: %s ", *(pp2+1));

2.3 Relaton between arrays and pointers

Here is an example, If we have an array:

char arr[5]="hello";
arr[0] equals to *(arr+0) 
arr[1] equals to *(arr+1) ……

So In fact, arr is a pointer to the first element of the array. So some people say in c, the use of [] is just syntactic sugar. And some even say that in C there are not actual arrays.

That is the basic concept and general usage of the C pointer. Hope it’s helpful!

猜你喜欢

转载自blog.csdn.net/weixin_44492824/article/details/127602321