鍍金池/ 問答/數(shù)據(jù)分析&挖掘  C/ c語言 數(shù)組操作異常

c語言 數(shù)組操作異常

main函數(shù)接收子函數(shù)處理的數(shù)組,遍歷數(shù)組時異常

示例代碼:

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

        //可變數(shù)組
        list = (char **)malloc(sizeof(char));

        demo(list);

        printf("\n");
        for(i=0; i < len; i++) {
            printf("%d=>%s\n", i, list[i]);
        }
}
回答
編輯回答
葬愛
#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需根據(jù)文本長度進(jìn)行改變
                sprintf(name, "root%d", i);
                list[i] = name;
                printf("%d=>%s\n", i, list[i]);
        }
}
void main()
{
        char **list;
        int i, len=10;

        //可變數(shù)組
        list = (char **)malloc(sizeof(char *)*len);

        demo(list);

        printf("\n");
        for(i=0; i < len; i++) {
            printf("%d=>%s\n", i, list[i]);
        }
}
2017年3月26日 22:32
編輯回答
冷咖啡
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 可變數(shù)組(variable length array).

2017年8月7日 13:25