c语言 数组操作异常

main函数接收子函数处理的数组,遍历数组时异常

示例代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void demo(char *list[])
{
        int i;
        char name[10];

        for (i=0; i< 10; i++) {
                sprintf(name, "root%d", i);
                list[i] = name;
                printf("%d=>%s\n", i, list[i]);
        }
}
void main()
{
        char **list;
        int i, len=10;

        //可变数组
        list = (char **)malloc(sizeof(char));

        demo(list);

        printf("\n");
        for(i=0; i < len; i++) {
            printf("%d=>%s\n", i, list[i]);
        }
}
阅读 2.7k
2 个回答
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void demo(char *list[])
{
        int i;
        char *name;
        for (i=0; i< 10; i++) {
                name = (char *)malloc(sizeof(char)*6);//这里的6需根据文本长度进行改变
                sprintf(name, "root%d", i);
                list[i] = name;
                printf("%d=>%s\n", i, list[i]);
        }
}
void main()
{
        char **list;
        int i, len=10;

        //可变数组
        list = (char **)malloc(sizeof(char *)*len);

        demo(list);

        printf("\n");
        for(i=0; i < len; i++) {
            printf("%d=>%s\n", i, list[i]);
        }
}
list = (char **)malloc(sizeof(char));

list only point to a memory area whose size is one char, that's far more from enough. It will cause segment fault

The solution is to allocate enough for list:

const int N = 200; // N is the maximux length of each string
char **list = malloc(len * sizeof(char *)); // Allocate row pointers
for(i = 0; i < nrows; i++)
{
    list[i] = malloc(N * sizeof(char)); 
}

...

//don't forget free!
for ( i = 0; i < len; i++ )
{
    free(list[i]);
}
free(list); 

BTW, the array allocated with the form of malloc is not 可变数组(variable length array).

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进