Learning about pointers in C language

Source: Internet
Author: User

pointers are a widely used data type in the C language. The use of pointer programming is one of the most important styles of C language. Pointer variables can be used to represent various data structures, easy to use arrays and strings, and can be processed as assembly language memory address, so as to compile a concise and efficient program. Pointers greatly enrich the functionality of the C language. Learning pointers are the most important part of learning C, and the ability to correctly understand and use pointers is a sign of our mastery of C language. At the same time, the pointer is the most difficult part of C language, in addition to the correct understanding of the basic concepts, but also must be multi-programming, on-Machine debugging. As long as this is done, the pointers are not difficult to master.

        basic concept of pointers in a computer, all the data is stored in memory. In general, a byte in memory is called a memory unit, different data types occupy a number of memory units, such as the integer 2 units, the character of 1 units, etc., in the second chapter has been described in detail. In order to access these memory cells correctly, each memory unit must be numbered. The internal memory element can be found accurately based on the number of a single cell. The number of the memory unit is also called the address. Since the memory unit can be found according to the number or address of the memory unit, it is often referred to as a pointer. The contents of a memory unit's pointer and memory unit are two different concepts. You can use a popular example to illustrate the relationship between them. When we go to the bank to deposit and withdraw money, the bank staff will find our deposit slip according to our account number and find the amount of deposit and withdrawal in the certificate. Here, the account is the deposit certificate of the pointer, the deposit number is the contents of the certificate. For a memory unit, the address of the cell is a pointer, and the data that is stored is the contents of the cell. In the C language, a variable is allowed to hold a pointer, which is called a pointer variable. Therefore, the value of a pointer variable is the address of a memory cell or a pointer to a memory unit. Figure, with the character variable C, the content is "K" (ASCII code is a decimal number), C occupies the 011A unit (address in 16 in number). With the pointer variable p, the content is 011A, in this case we call the P-point variable C, or P is a pointer to the variable C. Strictly speaking, a pointer is an address and is a constant. A pointer variable can be given a different pointer value, which is variable. But the pointer variable is often referred to as a pointer. In order to avoid confusion, we agree that "pointer" means an address, a constant, and a "pointer variable" refers to a variable that takes a value as an address. The purpose of defining pointers is to access the internal deposit cells via pointers.

since the value of the pointer variable is an address, the address can be not only the address of the variable, but also the address of other data structures. In a pointer variable, hold a
What is the meaning of the first address of an array or a function? Because arrays or functions are stored continuously. The array or function is found by accessing the pointer variable to get the first address of the array or function. In this way, wherever an array is present, the function can be represented by a pointer variable, provided that the pointer variable is given the first address of the array or function. Doing so will make the concept of the program very clear and the procedure itself concise and efficient. In the C language, a data type or structure often occupies a contiguous set of memory units. The concept of "address" does not describe a data type or structure well, while a "pointer" is actually an address, but it is the first address of a data structure, which is "pointing" to a data structure, so that the concept is clearer and more explicit. This is also an important reason to introduce the concept of "pointer".



File-type pointers




#include <stdio.h>

int main ()

{

int *ptr; declares an int pointer

int val = 1; declares an int value

PTR = &val; Assigning a reference to an int value for a pointer

int deref = *ptr; value the pointer to print the contents stored in the pointer address

printf ("Deref address =%ld, value =%d\n", PTR, deref);

}

Line 2 , we declare an int pointer through the * operator . Then we declare an int variable and assign a value of 1. We then initialize our int pointer with the address of the int variable . Next, the int pointer is evaluated, and the int pointer is initialized with the memory address of the variable . Finally, we print out the output variable value, the content is 1.

the &val of line 6 is a reference. after the Val variable declares and initializes the memory, by using the address operator before the variable name & We can directly reference the memory address of the variable.

Line 8 , we once again use the * operator to value the pointer, you can directly get the data in the memory address pointed to by the pointer. Since the type of the pointer declaration is int, the value taken is the int value stored by the memory address pointed to by the pointer .

Pointers and Arrays

#include <stdio.h>

int main ()

{

Intmyarray[4] = {1,2,3,0};

int *ptr = myarray;

printf ("PTR address =%ld, value *ptr=%d\n", ptr,*ptr);

ptr++;

printf ("PTR address =%ld, value *ptr=%d\n", ptr,*ptr);

ptr++;

printf ("PTR address =%ld, value *ptr=%d\n", ptr,*ptr);

ptr++;

printf ("PTR address =%ld, value *ptr=%d\n", ptr,*ptr);

}

the C-language array represents a contiguous memory space used to store multiple objects of a specific type. In contrast, pointers are used to store a single memory address. Arrays and pointers are not of the same structure and therefore cannot be converted to each other. The array variable points to the memory address of the first element of the array.

An array variable is a constant. You cannot assign a pointer to an array variable, even if the pointer variable points to the same address or to a different array. It is also not possible to assign an array variable to another array. However, it can be confusing to assign an array variable to the pointer. When assigning an array variable to a pointer, it is actually assigning the address to the first element of the array to the pointer.

Pointers and structures

#include <stdio.h>

struct Person {

Intage

Char *name;

};

int main ()

{

struct person first;

struct person *ptr;

First.age = 21;

Char *fullname = "full name";

First.name = fullname;

Ptr= &first;

printf ("age=%d, name=%s\n", First.age, Ptr->name);

}

#include <stdio.h>

#include <stdio.h>

#include <conio.h>

#include <string.h>

#include <stdlib.h>

Main ()

{

int Count,*array; /*count is a counter,array is an integer pointer, or it can be interpreted as pointing to the first address of an integer array */

if ((array= (int *) malloc (10*sizeof (int))) ==null)

{

printf ("The storage space cannot be allocated successfully.") ");

Exit (1);

}

for (count=0;count<10;count++)/* assign a value to an array */

Array[count]=count;

for (count=0;count<10;count++)/* Print array elements */

printf ("%d-", Array[count]);

}

The above example dynamically assigns the10An integer storage area, then assign and print. In the exampleif ((array= (int *) malloc (10*sizeof (int))) ==null)A statement can be divided into the following steps:
1) Allocation10integer, and returns an integer pointer to its start address
2) Assign this integer pointer address to theArray
3) to detect whether the return value isNull
2,Freefunction
because the area of memory is always limited, it cannot be allocated indefinitely, and a program should try to conserve resources so that when the allocated memory area is not used, it should be released for other variables or programs to use. Then we need to useFreefunction.
its function prototypes are:
void free (void *p)
function is to release the pointerPThe memory area that is pointing to.
its parametersPmust be a previously calledMallocfunction orCallocthe pointer that is returned when the function (another function that dynamically allocates the storage area). GiveFreethe function passing other values is likely to cause a crash or other catastrophic consequence.
Note: What is important here is the value of the pointer, not the pointer itself that is used to request dynamic memory. Example:
int *p1,*p2;
P1=malloc (10*sizeof (int));
P2=P1;
......
Free (p1)/*orFree (p2) */
MallocThe return value is assigned to theP1, and putP1value is assigned to theP2, so at this pointP1,P2are available asFreethe parameters of the function.
Mallocfunctions are allocated to the storage area.
FreeThe function is to free areas of memory that are already unused.

malloc function
the prototype of the malloc function is:
void *malloc (unsigned int size)
The function is to allocate a continuous space of size in the dynamic storage area of memory . Its argument is an unsigned number, and the return value is a pointer to the starting address of the allocated contiguous storage domain. It is also important to note that a NULL pointer is returned when the function fails to allocate storage space (such as low memory) successfully . Therefore, the function should be called to detect if the return value is NULL and perform the appropriate operation.



Experience:


Classroom to teach a lot about C language grammar rules, it sounds very dull, it is not easy to remember, rote memorization is not advisable. However, to use the C language tool to solve practical problems, but also must master it. Through the practice of many times on the computer, the knowledge of grammar has a perceptual understanding, deepen its understanding, on the basis of understanding will naturally grasp the C language grammar provisions. For some content oneself think in the classroom understand, but on the machine practice will find original (reproduced from the first. The deviation of understanding is due to the fact that most of the students are first contact with program design and lack of programming practice.

Learning C language can not stay in learning its grammatical rules, but use the knowledge learned to write C language programs, solve practical problems. That is, the C language as a tool, describing the steps to solve the actual problem, by the computer to help us solve problems. Only by the computer can you test whether you know the C language, the program you write to solve the problem correctly.


Learning about pointers in C language

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.