1. 下面程序输出是什么?
a+b=-1
a+b=4294967295
>6 // int -> unsigned int
a+b=1
a+b=1
<=8
void func(void)
{ unsigned int a;
int b = -7;
a=6;
printf("a+b=%d\n", a+b);
printf("a+b=%u\n", a+b);
(a+b>6)? puts(">6"):puts("<=6");
a=8;
printf("a+b=%d\n", a+b);
printf("a+b=%u\n", a+b);
(a+b>8)? puts(">8"):puts("<=8");
}
2. 下面程序输出是什么
m is 60fef8
m+1 is 60fefc
m[0] is 60fef8
ptr is 60ff0c, 5 // (int *)(&m+1)是移动一个数组长度
#include "stdio.h"
int main()
{
int m[5]={1,2,3,4,5};
int *ptr = (int *)(&m+1);
printf("m is %x \n",m);
printf("m+1 is %x \n",m+1);
printf("m[0] is %x \n",&m[0]);
printf("ptr is %x, %d \n",ptr, *(ptr-1));
return 1;
}
3.大小端
16bit宽的数0x1234在小端内存中的存放方式
0x4000 ---> 0x34
0x4001 ---> 0x12
16bit宽的数0x1234在大端内存中的存放方式
0x4000 ---> 0x12
0x4001 ---> 0x34
4.以下程序输出是什么
1)因为GetMemory并不能传递动态内存,Test()中的str一直都是NULL,strcpy程序崩溃。
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
2)因为GetMemory返回的是栈指针,GetMemory()执行后,其原内容已被清除,新内容未知,所以输出可能是乱码。
char *GetMemory(void)
{
char p[] = "hello world";
printf("p:%x\n", p);
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf("str:%x\n", str);
printf(str);
}
3)可以输出hello,但是有内存泄漏
#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);
}