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", );