资料C++c

C语言面试相关知识点

2016-01-29  本文已影响375人  yuanwang942217

c语⾔言语法,常⽤用数据结构

char *p = “hello”;
 char a[] = “hello”;
#define MIN(a,b) ((a)>(b)?(b):(a))
延伸:
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
-(void)methods
{int i = 4;//栈内存int* ptr = &i;//栈内存ptr = malloc(100);//堆内存,得到的是否是连续可操作的内存?
}

递归 的栈内存 一直没有释放,导致性能低下

a = a + b; 
b = a – b; 
a = a – b;
a = a ^ b;
 b = a ^ b; 
a = a ^ b;
计算sizeof的值
void *p = malloc(100);
sizeof(p)= ?;
void Func(char str[100]){
sizeof(str) = ?;}
  (1)void GetMemory(char *p){
 p = (char *)malloc(100);
}
void Test(void){
 char *str = NULL; 
GetMemory(str); 
strcpy(str, "hello world"); 
printf(str);
}

运行Test函数的结果是程序崩溃。因为GetMemory并不能传递动态内存,Test函数中的 str一直都是 NULL。strcpy(str, "hello world");将使程序崩溃。

(2)char *GetMemory(void){
 char p[] = "hello world";
return p;
}
void Test(void){
 char *str = NULL; 
str = GetMemory(); 
printf(str);
}

运行Test函数的结果可能是乱码。因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是 NULL,但其原现的内容已经被清除,新内容不可知。

(3)void GetMemory2(char **p, int num){
 *p = (char *)malloc(num);
}
void Test(void){
 char *str = NULL; 
GetMemory(&str, 100); 
strcpy(str, "hello"); printf(str);
}

运行Test函数的结果是:(1)能够输出hello(2)内存泄漏

(4)void Test(void){
char *str = (char *) malloc(100);
strcpy(str, “hello”);
free(str);
if(str != NULL){
strcpy(str, “world”);
 printf(str); 
    }
}

运行Test函数的结果是:篡改动态内存区的内容,后果难以预料,非常危险。因为free(str);之后,str成为野指针,if(str != NULL)语句不起作用。

 strcpychar *strcpy(char *strDest, const char *strSrc);
strcpychar *strcpy(char *strDest, const char *strSrc){
assert((strDest!=NULL) && (strSrc !=NULL));
char *address = strDest;
while( (*strDest++ = * strSrc++) != ‘\0’ )
 NULL ; 
return address ;
}

(2)strcpy能把strSrc的内容复制到strDest,为什么还要char * 类型的返回值?答:为了实现链式表达式。

例如 int length = strlen( strcpy( strDest, “helloworld”) );

4.完成下面函数以实现使用辗转相除法获取两个数(假设两个数都大于0)的最大公约数example: gcd(20,5 ) = 5. gcd(3,10 ) = 1. gcd(1620,1280 )= 20.

unsigned int gcd(unsigned int a,unsigned int b){
if (a < b) {
        gcd(b, a);
    }
    return b==0?a:gcd(b, a % b);
}
#include <stdio.h>
int main(int argc, const char * argv[]) {
    int a[5] = {1, 2, 3, 4, 5};
    int *ptr = (int *)(&a+1);
    printf("*(a+1) = %d \n*(ptr-1) = %d\n", *(a+1), *(ptr-1));
    // 注意 a[2] 2[a]输出的结果是一样的,因为a[2] = *(a + 2)而 2[a] = *(2 + a)
    printf("a[2] = %d\n2[a] = %d",a[2],2[a]);
    return 0;
*(a+1) = 2 
*(ptr-1) = 5
a[2] = 3
2[a] = 3
}
void swap_sort(int *p, int n) {
 int i ,j;
 int tmp; 
for(i=0; i<n-1; i++) {
 for(j=0; j<n-1-i; j++) { 
if(p[j]>p[j+1]) {
 tmp=p[j]; 
p[j]=p[j+1]; 
p[j+1]=tmp;
}
}
}
}
上一篇 下一篇

猜你喜欢

热点阅读