简单C测试程序出现段异常,求指教
简单C测试程序出现段错误,求指教
就这么简单一个C程序,scanf输入3个以内字符,运行没有问题,输入4个或4个以上就会出现段错误,求解~
通过argv[1]输入字符串是没有长度问题的。
------解决方案--------------------
char *str; 没有帮 str 分配空间啊
可以
const int MAX_SIZE 100; //你可能输入的最长
char str[MAX_SIZE];
------解决方案--------------------
char *str;未分配空间。
char array[len+1];不能用变量直接定义数组大小。
可用malloc或者new。用完释放。
- C/C++ code
#include <stdio.h> #include <string.h> #include <assert.h> int main(int argc, char *argv[]) { char *str; scanf("%s",str); //assert(argv[1] != NULL); int len = strlen(str); //int len = strlen(argv[1]); char array[len+1]; int i; for(i = 0; str[i] != '\0'; i++) { array[i] = str[i]; //array[i] = argv[1][i]; } array[len] = '\0'; printf("%s\n",array); return 0; }
就这么简单一个C程序,scanf输入3个以内字符,运行没有问题,输入4个或4个以上就会出现段错误,求解~
通过argv[1]输入字符串是没有长度问题的。
------解决方案--------------------
char *str; 没有帮 str 分配空间啊
可以
const int MAX_SIZE 100; //你可能输入的最长
char str[MAX_SIZE];
------解决方案--------------------
char *str;未分配空间。
char array[len+1];不能用变量直接定义数组大小。
可用malloc或者new。用完释放。
- C/C++ code
#include <stdio.h> #include <stdlib.h> #include <string.h> int main( ) { char str[30]; scanf("%s",str); int len = strlen(str); char *array=(char *)malloc(len+1); int i; for(i = 0; str[i] != '\0'; i++) { array[i] = str[i]; } array[len] = '\0'; printf("%s\n",array); free(array); system("pause"); return 0; }