Cannot pass the pointer variable itself to a function

Source: Internet
Author: User

Example 1: #include <stdio.h> #include <stdlib.h>void fun (char*p) {char c = p[3];//or char c=* (p+3);} int main () {char*p2 = "ABCDEFG"; Fun (p2); system ("pause"); return 0;} Error, because the pointer variable itself cannot be passed to a function should make a copy of the argument and pass it to the called function, that is, to make a copy of the P2, assuming its copy is named _P2, which is passed to the inside of the function is _P2, not P2 itself. Example 2:void getmemory (Char*p,int num) {p = (char*) malloc (num*sizeof (char));} int main () {char*str=null; GetMemory (str,10); strcpy (str, "Hello"); free (str); return 0;}


in the Run strcpy (str, "Hello") When an error occurs, STR is still null, that is, str itself does not change, malloc's memory address is not assigned to STR, but is assigned to _STR, and _str is the compiler automatically allocated and recycled, we simply can not use, so we can not get memory. There are two ways to do this:

Law one: with return

#include <stdio.h> #include <stdlib.h>char*getmemory (char*p,int num) {p = (char*) malloc (num*sizeof (char)) ; return p;} int main () {char*str=null;str=getmemory (str,10); strcpy (str, "Hello"),//free (str);p rintf ("%s\n", str); system ("Pause "); return 0;}


Results:

Hello

Please press any key to continue ...

Method Two : With a level two pointer

#include <stdio.h> #include <stdlib.h>void getmemory (char**p,int num) {*p = (char*) malloc (num*sizeof (char) ); return p;} int main () {char*str=null; GetMemory (&str,10); strcpy (str, "Hello"),//free (str);p rintf ("%s\n", str); system ("pause"); return 0;}

Note that the parameter here is &str rather than STR, so passing in the past is the address of STR, is a value, inside the function, with the key ("*") to unlock: * (&STR), the value is str. So malloc allocates a memory address that is really assigned to the STR itself


Cannot pass the pointer variable itself to a function

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.