基础知识 | 每日一练(197)

  • 2019 年 12 月 9 日
  • 筆記

读者:交换两个变量的值,不使用第三个变量。即a=3,b=5,交换之后小林:

a=5,b=3;有两种解法, 一种用算术算法, 一种用^(异或)

a = a + b;

b = a – b;

a = a – b;

or

a = a^b;// 只能对int,char..

b = a^b;

a = a^b;

or

a ^= b ^= a;

读者:c和c++中的struct有什么不同?

小林:

c和c++中struct的主要区别是c中的struct不可以含有成员函数,而c++中的struct可以。c++中struct和class的主要区别在于默认的存取权限不同,struct默认为public,而class默认为privat

读者:这个程序有什么问题

#include <stdio.h>

#include <stdlib.h>

void getmemory(char *p)

{

p=(char *) m alloc(100);

strcpy(p,"hello world");

}

int m ain( )

{

char *str=N U LL;

getmemory(str);

printf("% s/n",str);

free(str);

return 0;

}

小林:

程序崩溃,getmemory中的malloc不能返回动态内存,free()对str操作很危险。

读者:

char szstr[10];

strcpy(szstr,"0123456789");

产生什么结果?为什么?

小林:长度不一样,会造成非法的OS