c - 填充动态 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++;
}
解决方案
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 */
}
}
推荐阅读
- numpy - 当 vstack 不工作时,如何垂直堆叠矩阵?
- python - ctypes vs _ctypes - 为什么后者存在?
- python - Why python super() not working without parameters in ABCMETA class?
- python-3.x - Tkinter tag_lower“标签搜索表达式中的布尔运算符无效”
- android - 一旦我尝试主要登录这一行,应用程序就会关闭 if (login.getType().equals("Admin") && login.getType() != null)
- r - 这个 R 函数如何返回值?
- java - 如何修复:“无法为 jboss-interceptors-api_1.2 导出模块描述符”
- python - 从 matplotlib 图中返回一个 numpy 数组太慢了,我该如何加快速度?
- python - 具有“动态常量”的 Python 工厂函数
- python - 即使列中的单个值不是 NaN,如何过滤 Coulmns