• 昨天面试遇到的一道C语言题


    楼主之前是做C/C++开发的,今年转到java,hadoop方向了,所以很多C/C++的细节都有些模糊了,碰巧这次面试题中,就出了一道C指针的问题。

    问题不算难,但楼主一时之间竟也想不起来答案了。。。

    这道题给出了一小段程序,要你写出结果,程序如下:

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 
     5 void func(char *p) 
     6 {
     7         p = (char *) malloc (1000);
     8 }
     9 
    10 int main(void)
    11 {
    12         char *p = NULL;
    13 
    14         func(p);
    15 
    16         strncpy(p, "hello", strlen("hello"));
    17 
    18         printf("p = %s
    ", p);
    19 }

    这道题主要考察了“指针变量”的概念,char *p中,p就是指针变量,其中存放了所指向变量的地址。

    当p作为实参传入func函数时,形参中的char *p中的p也时一个局部变量,也就是说,在func函数中,p变量的变化,并不会引起main函数中p的改变。

    所以即便在func函数中,给p申请了空间,但main函数中的p仍旧是NULL指针,所以本题的答案应该是:

    段错误

    如果需要程序正常运转,需要将程序修改成:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void func(char **p) 
    {
            *p = (char *) malloc (1000);
    }
    
    int main(void)
    {
            char *p = NULL;
    
            func(&p);
    
            strncpy(p, "hello", strlen("hello"));
    
            printf("p = %s
    ", p);
    }

    即在main函数调用func函数时,传入p的地址,从而完成在func函数中修改main中的p值。

    当然,在实际开发过程中,应该尽量避免这种内存申请的方式,因为申请和销毁如果分开执行,很容易会忘记执行销毁程序,从而造成内存泄漏。

  • 相关阅读:
    测试种类
    Android ADB使用之详细篇
    Maven 生命周期
    在Eclipse中新建Maven项目
    Maven搭建环境(Linux& Windows)
    一个简单的JUnit项目
    Assertions
    Aggregating tests in suites
    Test execution order
    c#一个分页控件的例子
  • 原文地址:https://www.cnblogs.com/xyliao/p/5746716.html
Copyright © 2020-2023  润新知