常见的C语言面试编程题(三)

1,航天二院某所面试题,考查的是结构体和数组的内存布局情况。

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

 

typedef struct array1{
int ID;
struct array1* next;
}A;

 

typedef struct array2{
int ID;
int a;
int b;
int c;
}* B;

 

int main()

{


A s1[15];
A* s2;
B s3;
for(int i=0;i<10;i++)
{
s1[i].ID=i+64;
}
s2=s1+3;
s3=(B)s2;
printf("%d/n",s3->b);
return 0;

}

 

2,某通信企业的面试题目,从字符串数组和指针字符串在内存中的分配情况考查指针的使用。

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

 

char *GetMemory(char *p)
{
p = (char *)malloc(100);
return p;
}//当调用此函数时,会在栈里分配一个空间存储p, p指向堆当中的一块内存区,当函数调用结束后,若函数没有返回值,
//系统自动释放栈中的P

void Test(void)
{
char *str = NULL;
str=GetMemory(str);
strcpy(str, "test");
printf("%s/n",str);
}


char *GetMemory1(void)
{
char *p = "Test1";
return p;
}//若换成char p[]="hello world"; 就会在函数调用结束后,释放掉为"Test1"的拷贝分配的空间,返回的P只是一个野指针

void Test1()
{
char *str = "";
str=GetMemory1();
printf("%s/n",str);
//str=GetMemory();
}

void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
}//当调用此函数时,会在栈里分配一个空间存储p, p指向栈中的一变量str,在此函数中为str在堆当中分配了一段内存空间
//函数调用结束后,会释放p, 但str所在的函数Test2还没运行完,所以str此时还在栈里.

void Test2(void)
{
char *str = NULL;
GetMemory2(&str, 100);
strcpy(str, "hello");
printf("%s/n",str);
}

void Test3(void)
{
char *str=(char *)malloc(100);
strcpy(str, "hello");//此时的str指向的是拷贝到栈里的"hello",所以当释放掉str指向的堆空间时,str指向的栈里的值还是不变
free(str);
if(str   != NULL)
{
 
strcpy(str, "world");
printf("%s/n",str);
}
}

 

int main()
{
Test();
Test1();
Test2();
Test3();
}

3,c语言中sizeof的用法

void fun(char s[10])
{
printf("%s/n",s);
printf("%d/n",sizeof(s));//引用的大小
}

int main()

{

char str[]={"sasdasdes"};

printf("%d/n",sizeof(str));//字符串数组的大小10(包含了字符'/0')

printf("%d/n",strlen(str)));//字符串的长度9
char *p=str;

printf("%d/n",sizeof(p));//指针的大小4

printf("%d/n",strlen(p));//字符串的长度9


fun(str);

void *h=malloc(100);
char ss[100]="abcd";
printf("%d/n",sizeof(ss));//字符串数组的大小100

printf("%d/n",strlen(ss));//字符串的长度4
printf("%d/n",sizeof(h));//指针的大小4

}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值