The landlord before is to do C/d ' java,hadoop, this year turn to the direction of the, so a lot of the details are somewhat blurred, C/C + +, it happened that the interview problem, on the issue of a pointer.
The problem is not difficult, but the landlord in a moment unexpectedly also can't think up the answer ...
This problem gives a short procedure, you want to write the results, the program is as follows:
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5 voidFuncChar*p)6 {7p = (Char*)malloc( +);8 }9 Ten intMainvoid) One { A Char*p =NULL; - - func (p); the -strncpy (P,"Hello", strlen ("Hello")); - -printf"p =%s\n", p); +}
This problem mainly examines the concept of "pointer variable", in Char *p, p is the pointer variable, which holds the address of the pointed variable.
When P is passed as an argument to the Func function, the p in the Char *p in the formal parameter is also a local variable, that is, in the Func function, the change of p variable does not cause p in the main function to change.
So even in the Func function, p is applied for space, but p in the main function is still a null pointer, so the answer to this question should be:
Segment Error
If you need a program to function properly, you need to modify the program to:
#include <stdio.h>#include<stdlib.h>#include<string.h>voidFuncChar**p) {*p = (Char*)malloc( +);}intMainvoid){ Char*p =NULL; Func (&p); strncpy (P,"Hello", strlen ("Hello")); printf ("p =%s\n", p);}
That is, when the main function calls the Func function, the address of P is passed in to modify the P-value in main in the Func function.
Of course, in the actual development process, you should try to avoid this kind of memory application, because the application and destruction if executed separately, it is easy to forget to execute the destruction program, resulting in a memory leak.
Yesterday's interview with a C language problem