首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

简单C测试程序出现段异常,求指教

2012-04-24 
简单C测试程序出现段错误,求指教C/C++ code#include stdio.h#include string.h#include assert.hint

简单C测试程序出现段错误,求指教

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;} 

热点排行