iOS Basics Getting Started--malloc method

Source: Internet
Author: User

char m;

scanf ("%c", &m); // preceded by a space to remove the space, carriage return and other operations

NSLog (@ "The character is%c", m);


Above this program is you are more familiar with the two methods an input, an output, but if I change to change to


Char *m;

NSLog (@ "\ n Please enter a character ");

scanf ("%c", M);

NSLog (@ "\nthis is%c", *m);


Is it correct to compile with an error and will the runtime have problems?

In fact, this program, if the compiler does not occur when the exception, but if run, there will be a run-time exception (the LLDB command, the end of the Kill command), because we have defined a char pointer m, the pointer is not initialized assignment, Causes the program to run without finding the memory space to store the character, if changed to


Char *m;

m= (char *) malloc (sizeof(char)); malloc () dynamically allocates memory , allocates the first address of memory with malloc, and assigns a value to m

NSLog (@ "\ n Please enter a character ");

scanf ("%c", M);

NSLog (@ "\nthis is%c", *m);


      if the malloc method is used to allocate space, the program can proceed normally, and the sizeof method gets the space size of the corresponding type


When it is hot again, because we use malloc to dynamically allocate space, we can use a char pointer to output a string, as follows:

Char *a;

A= (Char *)malloc(sizeof(char) *); // Dynamic Allocation - a continuous Char memory Address

NSLog (@ "\ n Please enter a string ");

scanf ("%s", a);

NSLog (@ "\nthis is%s", a);







iOS Basics Getting Started--malloc method

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.