Basic ios entry-malloc Method

Source: Internet
Author: User

Basic ios entry-malloc Method

Char m;

Scanf ("% c", & m); // a space is added to the front to remove spaces and press Enter.

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


The above program is familiar with two methods: one input and one output, but if I change it


Char * m;

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

Scanf ("% c", m );

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


Is it correct? Will an error be reported during compilation and a problem occur during runtime?

In fact, this program will not be abnormal during compilation, but if it is run, it will be abnormal during running (the lldb command will appear, and you can end with the kill command ), the reason is that we have defined a char pointer m, which is not initialized and assigned a value. As a result, the memory space for storing this character cannot be found during the program running. If it is changed


Char * m;

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

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

Scanf ("% c", m );

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


If you use the malloc method to allocate space, the program can proceed normally. the sizeof method gets the size of the corresponding type of space.


We can use the char pointer to output the string as follows:

Char *;

A = (char *) malloc (sizeof (char) * 100); // dynamically allocate 100 consecutive char memory addresses

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

Scanf ("% s", );

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







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.