虽然一直想找个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();
}