C/C++学习中遇到的有关问题总结(进行时)
C/C++学习中遇到的问题总结(进行时)
1
错误信息: incompatible implicit declaration of built-in function ‘malloc’
解决方法: 加入 #include <stdlib.h>
2 错误信息: strcpy 时 出现段错误。
解决方法: strcpy 的第一个参数是只读导致的,所以判断strcpy的第一个参数是否是只读。
例子
#include <stdio.h> #include <string.h> #include <stdlib.h> void LoopMove(char *source,int steps) { char *temp =(char *)malloc(strlen(source)+1); if(temp != NULL) { printf("malloc true\n"); }else { printf("f"); temp = (char *)malloc(100); } strcpy(temp,source); int len = strlen(source)-steps; strcpy(source+0,temp+len); strcpy(source+steps,temp); *(source+strlen(temp))='\0'; } int main(void) { char s[] ="abcd1234"; LoopMove(s,3); printf("%s\n",s); return 0; }
上述main 函数修改如下
int main(void) { char *s ="abcd1234"; LoopMove(s,3) ;//或者 LoopMove("abcd1234",3); printf("%s\n",s); return 0; }
则会出现“段错误”的异常。
原因是 char *s = "abcd1234";
s 指向了一个字符串常量区域,是不能修改的。在编译阶段就已经确定的。
而采用数组的方式是动态的创建,位于函数变量栈中。