几道C语言笔试题及个人理解

虽然一直想找个Golang相关的工作,也拿了几个offer,但确没有一个心仪的,只能转找C语言了。下面是某新三板上市公司的笔试题,感觉挺有意义的,分享出来。

第0题 本题输出hello,因为GetMemory传入的p是指针。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void GetMemory(char **p, int num)
{
    *p = (char *)malloc(num);
}

void Test(void)
{
    char *str = NULL;
    GetMemory(&str, 100);
    strcpy(str, "hello");
    printf(str);
}

void main()
{
    Test();
}

第1题 本题输出world,因为free只是释放内存,并不等于NULL

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void Test(void)
{
    char *str = (char *)malloc(100);
    strcpy(str, "hello");

    free(str);

    if (str != NULL)
    {
        strcpy(str, "world");
        printf(str);
    }
}

void main()
{
    Test();
}

第2题 本题无输出,或者输出乱码,因为GetMemory里面的p为局部变量,在GetMemory返回时被释放。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *GetMemory(void)
{
    char p[] = "hello world";
    return p;
}

void Test(void)
{
    char *str = NULL;
    str = GetMemory();
    printf(str);
}

void main()
{
    Test();
}

第3题 本题输出hello world;请注意这道题和第2题的区别,第2题的GetMemory中的char p[]是函数的局部变量存储在栈中,随函数返回被释放;本题GetMemory中的“hello world”分配到静态存储区,p指向其,在函数返回时并不会被释放。
具体的请自行搜索引擎char p[] = “hello world”和char *p = “helloworld”的区别。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *GetMemory(void)
{
    char *p = "hello world";
    return p;
}

void Test(void)
{
    char *str = NULL;
    str = GetMemory();
    printf(str);
}

void main()
{
    Test();
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值