c - 为什么当我放入值时,我的二维数组在索引处显示正确的值,而不是我稍后尝试访问它们的值? (C)

标签 c arrays pointers dynamic-memory-allocation

我正在编写一个程序,该程序读取 Linux 影子文件,将每一行分隔为 ID、盐和加密密码的哈希值。我为每个值创建了一个二维字符数组,并在浏览每一行时用这些值填充它。当我将这些值输入到数组中时,我将其打印出来只是为了表明它正在输入正确的值,如下所示:

printf(id: %s, salt: %s", ids[num_accounts], salts[num_accounts]);

结果如下:

id: root, salt: NrF46O1p
id: seed, salt: wDRrWCQz
id: user1, salt: LGOwUL7Q
id: user2, salt: CL5Fr2bN
id: user3, salt: Un/lqxkl
id: user4, salt: Lx2zrG31
id: user5, salt: 6R1eYOtL

这是在输入每个值时完成的。输入所有值并且程序退出 while 循环后,还有另一个 for 循环打印出所有值(用于调试目的)

for(int i = 0; i < num_accounts; i++){
     printf("salt %d: %s\n", i, salts[i]);

结果如下:

salt 0:
salt 1:
salt 2: 6R1eYOtL
salt 3: 6R1eYOtL
salt 4: 6R1eYOtL
salt 5: 6R1eYOtL
salt 6: 6R1eYOtL
salt 7: (null)

这是我分配二维数组并填充它的代码:

char **ids;
char **hashes;
char **salts;

hashes = malloc((num_accounts + 1) * sizeof(char*));
salts = malloc((num_accounts + 1) * sizeof(char*));
ids = malloc((num_accounts + 1) * sizeof(char*));

for(int i = 0; i < num_accounts; i++){
     hashes[i] = malloc(88);
     salts[i] = malloc(8);
     ids[i] = malloc(15);
}

shadow = fopen("shadow", "r");
num_accounts = 0;
while(fgets(shdw_line, SHDW_LINE_LEN, shadow)!=NULL){
     char *token = strtok(shdw_line, ":");
     char *shdw_hash = strtok(NULL, ":");
     if(strcmp(shdw_hash, "*")!=0 && strcmp(shdw_hash, "!")!=0){
        ids[num_accounts] = token;
        token = strtok(shdw_hash, "$");
        token = strtok(NULL, "$");
        salts[num_accounts] = token;
        token = strtok(NULL, "$");
        hashes[num_accounts] = token;
        printf("%d: id: %s, salt: %s\n", num_accounts, ids[num_accounts], salts[num_accounts]);
        num_accounts++;
     }
}

我想知道为什么数组会被最后输入的值覆盖?

最佳答案

salts[i] = malloc(8);

更改为

salts[i] = malloc(9);//多1个用于标记字符串结尾及其基本背景 知识

<小时/>

salts[num_accounts] = token;//会给你源字符串的指针,这样你就会得到相同的

更改为

strcpy(salts[num_accounts], token );

关于c - 为什么当我放入值时,我的二维数组在索引处显示正确的值,而不是我稍后尝试访问它们的值? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262509/

相关文章:

java - 在android中添加两个字节数组

c++ - VC++中通过A类函数指针调用B类成员函数

C++ 结构指针

c++ - 交换基本类型的对象会抛出异常吗?

C 结构和 printf

c++ - for 每个循环读取数组都是错误的

mysql - Codeigniter mysql程序多变量

javascript - 访问 Javascript 对象中的数组

c - 什么时候写入套接字 block ?

c - Errno : 11, 资源暂时不可用