首页  

几个有趣的C语言面试题及答案     所属分类 c 浏览量 688
涉及指针 进程 运算 结构体 函数 内存


gets 函数

#include "stdio.h" 
int main() { 
    char buff[9]; 
    memset(buff,0,sizeof(buff)); 
    gets(buff); 
    // fgets(buff, sizeof(buff), stdin);
    printf("%s\n",buff); 
    return 0; 
}

char* gets(char* buffer)
char* fgets(char* s, int n, FILE* stream)
fgets  最多只能读入n-1个字符
gets 可能导致缓存溢出

MAC 下运行 提示
warning: this program uses gets(), which is unsafe.


strcpy 函数 char *strcpy(char *dest,char *src) char * strncpy(char *dest, char *src, size_tn) #include "stdio.h" #include "string.h" int main(int argc, char *argv[]) { if(argc!=2){ printf("please input Password\n"); return 0; } int flag = 0; char passwd[9]; memset(passwd,0,sizeof(passwd)); // strcpy(passwd, argv[1]); strncpy(passwd, argv[1],sizeof(passwd)); if(0 == strcmp("hello", passwd)) { flag = 1; } if(flag) { printf("\n Password cracked \n"); }else { printf("\n Incorrect passwd \n"); } return 0; }
main()的返回类型 #include "stdio.h" #include "stdlib.h" int main(void){ char *ptr = (char*)malloc(10); if(NULL == ptr){ printf("\n Malloc failed \n"); return; } else{ // Do some processing // no free , memory leak // free(ptr); } return; } warning: return type of 'main' is not 'int' main()的返回类型应该是 int 而不是 void int 返回类型会让程序返回状态值
内存泄露 #include "stdio.h" #include "stdlib.h" int main(void){ char *ptr = (char*)malloc(10); if(NULL == ptr){ printf("\n Malloc failed \n"); return; } else{ // Do some processing // no free , memory leak // free(ptr); } return; }
使用_exit退出 #include "stdio.h" #include "stdlib.h" #include "unistd.h" void func(){ printf("\n Cleanup function called \n"); return; } int main(void){ int i = 0; atexit(func); for(;i<0xffffff;i++); _exit(0); // return 0; } _exit() 不会调用 atexit() 注册的函数
接受任何类型的参数并返回 int 的函数 int func(void *ptr)
*和++操作 #include "stdio.h" int main(void){ char* ptr = "Linux"; printf("%c",*ptr++); printf("%c\n",*ptr); return 0; } 输出 Li *ptr++ 相当于 *(ptr++)
修改只读字符串 #include "stdio.h" int main(void){ char* ptr = "Linux"; *ptr = 'A'; printf("%s\n",ptr); return 0; }
返回局部变量地址
#include "stdio.h" int* func(int value){ int a = value; a++; return &a; } int* func2(int* value){ (*value)++; return value; } int main(void){ int a = 9; int* p = func(a); printf("%d\n",*p); p = func2(&a); printf("%d\n",*p); printf("%d\n",a); return 0; }
#include "stdio.h" int main(void){ int a = 1,b=2,c=3; printf("%d %d %d\n",a+b+c,b*=2,c*=2); return 0; } MAC 下 编译警告 warning: unsequenced modification and access to 'b' warning: unsequenced modification and access to 'c' 输出 6 4 6 linux gcc version 4.8.5 20150623 (Red Hat 4.8.5-11) 编译无警告 输出 11 4 6

上一篇     下一篇
c++异常处理

c++菱形继承

c++ 虚函数多态

c 指针数组

二维数组函数入参用法

二维整型数组参数传递的三种方式