Yesterday's interview with a C language problem

Source: Internet
Author: User

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

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.