首页 > 解决方案 > 填充动态 char 数组会导致覆盖

问题描述

我有以下问题。我在 C 中分配了一个 2d 动态字符数组。但是,当我尝试在每一行中使用唯一字符串填充这个数组时,每个条目都会覆盖以前的条目。因此,我最终得到了一个数组,其中每个原始字符串中只有最后一个字符串。可以提供一些见解吗?谢谢你。

FILE *dictionary;
dictionary = fopen("dictionary.txt","r");

if (dictionary == NULL)
{
    printf("can not open dictionary \n");
    return 1;
}
char line[512];
char** hashes;
hashes = malloc(250*512);

if(!hashes){
    printf("OUTOFMEMORY\n");
    return;
}

i=0;
char *salt;
salt = extract_salt(shd);
char* encrypted;
while(fgets(line, sizeof(line), dictionary))
{
    //hashes[i] = calculate_hash(shd, line);
    encrypted = crypt(line, salt);
    printf("%s\n",encrypted );
    strcpy(hashes[i],encrypted );

    if(i>0)
        printf("%s, %s \n", hashes[i], hashes[i-1]);
    i++;
}

标签: cdynamic-memory-allocation

解决方案


char** hashes; 

这一行声明了一个指向 char 的指针,而不是二维数组。

您需要将初始化更改为:

char** hashes;
hashes = malloc(250 * sizeof(*hashes));

if(!hashes){
    printf("OUTOFMEMORY\n");
    return;
}

for(size_t index = 0; index < 250; index++)
{
   hashes[index] = malloc(512);
   if(!hashes[index]){
       /* memory allocation error routines */
   }
}

推荐阅读