C-language double pointer and malloc

Source: Internet
Author: User

(The content is mainly from the Internet, just added some of their own analysis)

Suppose there is a double pointer:

Char **p;

There is also an array of pointers

Char *name[4];

How to quote P? First we have the program code as follows

#include <stdio.h> int main () {     char *s = "I Love You";     Char *s1 = "You Love Me";     Char *s2 = "she Love You";     Char *s3 = "he love her";     Char *name[4];     Name[0] = s;     NAME[1] = S1;     NAME[2] = s2;     NAME[3] = S3;     char **p;     p = name + 2;     printf ("%d\n", *p);     printf ("%d\n", **p);     printf ("%c\n", **p); Why this print S    printf ("%d\n", p);     printf ("%d\n", *&p);     printf ("%d\n", &p);     printf ("%s\n", *p);  And this prints out the string    return 0;}

The output results are:

4333636

115

S

1244976

1244976

1244964

She Love You

Analysis:

1, p is a double pointer, which is itself a variable. Since it is a variable, it should store the value itself. This is the same as int i = 65; I stores the value 65. and P Stores the address, and the address is a numeric value. So when we print P, we print the value of the address stored in P, which is 1244976.

2, the same: printing *&p, we first take the address of P (&p), p is a variable, of course, it will have a storage address, and then we use * to use the value stored on the address, it is obviously the value of p this variable represents, of course, or 1244976.

3, we in the analysis with%d to print *p, why got 4333636. The reason is: P is a double pointer, so *p is still a one-pointer variable, and its specific representation can be * (P + 0). For ease of understanding, we assume that there is a char *row; row = * (p + 0); So we turn the problem into a one-dimensional pointer, we print *p, actually print row, so we can refer to the analysis (1).

4, analysis with%s to print *p, why got she love we can actually use Analysis (3) of the idea, this time, row represents the first address of this sentence, we pass the first address of the sentence, to print the string.

5, we will analyze with%d print **p why is 115; in fact, we can look at * (* (p + 0) + 0); This benefit can be simplified to become * (row + 0); Since row is a one-dimensional pointer, this (row + 0) represents the No. 0 of the string we want to print. The address of a character! Then we use * To use this address value, just is ' s ', then forget the ' s ' corresponding ACSII code is 115!

6. Analyze why%c can print ' s '. Analysis (5) It's all been said.

Related questions :

The wrong routine:

#include <stdio.h> #include <stdlib.h> #include <string.h>void getmemery (char *p) {    p= (char *) malloc (100);
The following line is for you to add
*p=1; In order to compare the problem where}void main () { char *str=null; Getmemery (str); strcpy (str, "Hello World"); printf ("%s", str); Free (str);}

At compile time, the runtime outputs a segment error.

In fact, the classic error in C (value transfer swap), why the first look is right, because we always think that pointer passing can be done, and then ignore the subsequent changes are valid.

The wrong thing to do is to pass in a pointer, but not to manipulate the pointer, but to manipulate the pointer variable. The operation of the pointer variable becomes the same as the original value of the transfer of swap, making it invalid for the pointer modification. Pointer variables are not much different from other ordinary types of variables, which is a nickname for a memory (except that the pointer variable represents the memory put in the address, the other type of variable is the data), after passing in the child function, only the value of the memory with the STR as a null address to the memory of the P-alias , the memory with P as its nickname is a nickname for another piece of memory through malloc. But after the child function is finished, back to the original main function, STR is the original STR, and there is no change or null pointer.

If you want it to be valid only, pass in the pointer to STR (the pointer variable is also the content of a piece of memory) [&STR] and the pointer operation (the 2nd method below), or the modified pointer variable is returned (the 1th method below).

A correction method:

#include <stdio.h> #include <stdlib.h> #include <string.h>char *getmemery (void)//By returning the pointer variable {    Char *p= (char *) malloc (+);    return p;} void Main () {    char *str=null;    str = Getmemery ();    strcpy (str, "Hello World");    printf ("%s", str);    Free (str);}

Another way to modify

#include <stdio.h> #include <stdlib.h> #include <string.h>void getmemery (void **p)//by using a double pointer {    * p= (void * *) malloc (100);} void Main () {    char *str=null;    Getmemery (&STR);    strcpy (str, "Hello World");    printf ("%s", str);    Free (str);}

Analyze why the previous program was wrong.

(1) void Getmemery (char *p)

(2) Char *str=null;

(3) Getmemery (str);

1 The parameter of the neutron program is a pointer, and then it is natural to think of 2,3 in the way of invocation, the original idea is to allocate memory with malloc, and then modify the incoming pointer variable, then finally according to through strcpy (str, "Hello World"); You can write data to the allocated memory. Everything is so smooth, right, because this usage is usually used, so it is not to consider the correctness.

However, there is a problem here. First, Getmemery (STR) passes the address of the SRT pointer, this is no problem, C is different from C + +, the arguments are passed through, not by reference. That is, the actual parameter str first copy their own copies, and then passed to the form parameter *p receive, the C language pointer has been emphasized many times, but I still wrong ah, haha.

Then, in the subroutine, if through *p then access to the content will be *str, this is equivalent. However, this procedure a fatal error, very covert, that is the subroutine attempt to modify the contents of P , not *p content !! This mistake has been looking for me for a long time finally to find out. It makes no sense to modify the value of P, which is a formal parameter and does not return anything, whereas *p accesses the required variable directly through the address of P, which is a different usage. So plainly, after the execution of void Getmemery (char *p) does not change anything, the value of STR has not been modified and remains null, so access to the *0 address is forbidden by the operating system and an error is obtained.

The solution is to use a 2-pointer. The goal is to modify the pointer's address, but according to the above analysis, we can not modify, but we could use a 2-pointer, the address value of the *str str, with 2 heavy pointers to change.

void Getmemery (void **p)
{
*p= (void * *) malloc (100);
}

The sub-program changes to this appearance, the parameters of the entry and exit must be modified

Char *str=null;
Getmemery (&STR);

So it can be understood, because the formal parameter is a 2-pointer, so p corresponds to &str, *p corresponds to STR, said before, our purpose is to modify the value of STR, so it is natural, we use *p = xxx such form to modify.

The procedure is correct.

 

Malloc

Standard 3:malloc + Free + pointer blank

malloc is applying for heap space

/*DATE:20100824DESCRIPTION:MALLOC usage specification discusses in parameters: the number of bytes of heap memory requested, note that Int,short,float needs to multiply the corresponding number of bytes.   Out return value: void **/main () {char *str=null;str= (char *) malloc (10);     Note The malloc return value is void *, and the request needs to be cast to the required type memset (str,0,10);  If not emptied, the application area value is random, develop good habit strcpy (str, "Happylife"); Use strcpy to pay particular attention to the copy of the string length <=10-1, that is, to reserve the string end flag ' puts ' (str), free (str);p rintf ("str[address]:%s[%x]\n", str,str);  The str content here is empty, but the pointer address is still str=null;  Note that the pointer still exists after the pointer is free, and it is best to point it to null. printf ("str[address]:%s[%x]\n", str,str);  The str content here is empty and the address is empty}

  

C-language double pointer and malloc

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.