gpt4 book ai didi

c - 虽然 C 中的循环分配没有按预期工作

转载 作者:行者123 更新时间:2023-12-01 23:08:33 24 4
gpt4 key购买 nike

尝试打印从按字母顺序排列的文件中读取的所有名称。

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

int compare(const void *a, const void *b){
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}

int main(int argc, char* argv[]){

//Takes input in terminal/cmd (filename.txt).
char *input = malloc(sizeof(char) * 50);
if (argc < 2){
printf("Enter filename: ");
scanf("%s", input);
} else
input = argv[1];
//.......................


int count = 0; //Names count
char *names[100]; //Pointers to each name in file
char str[50];
FILE *file;
file = fopen(input, "r");

//Allocate space for the pointers
for (int i = 0; i < 100;i++){
names[i] = malloc(sizeof(char) * (50 + 1));
}

//Adding names to array
if (file) {
while ((fgets(str, 50, file)) != NULL){
count++;
names[count] = str;
printf("%s", names[count]); //This will print names as read from file
}
fclose(file);
printf("%s", names[2]); //This will print the last name read with the while loop no matter the index of names[]

} else printf("Can't read from file");

//Sorting "names" in alphabetical order
int length = sizeof(names)/sizeof(char*); //length of names
qsort(names, length, sizeof(char*), compare);

//printing each name (will be the last string read by while loop times the length)
for(int i = 0; i < length; i++){
printf("%s", names[i]);

}
printf("%d", count); //printing names count
}

编译并运行该程序会得到以下输出:

Tredigar
Ghorvas
Wolvar
Lurtrum
Sabakzar
Hagan
Korlag
Malagar
Ferrek
Baelnar
Grimmalk
Roken
Vabul
Radek
Agaro
Krag
Balfam
Vistrum
Halzar
Maulnar
Auxlan
Krim
Borkul
Thorin
Morak
Arnan
Garmul
Avamir
Darkul
Bariken
Mardam
Hlant
Rogath
Melgar
Thorbalt
Dyrnar
Ezegan
Smethykk
Sharak
Swargar
Halagmar
Rozag
Orobok
Arval
Kurman
Erag
Dolmen
Glint
Haeltar
Haeltar
8┼Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
Haeltar
49

显然,我正在尝试按字母顺序对字符串进行排序。我当前的问题是,无论我在 while 循环外打印 names[] 的什么地方,指针都指向 Haeltar,这是 while 循环中分配的最后一个名字。我进行了广泛的搜索,但无法弄清楚是什么导致了这种行为。我对 C 编程比较陌生。

最佳答案

这个 names[count] = str; 为数组的每个成员分配 str 的地址。他们都指向它。所以很自然地,它们都指向 "Haeltar",这是最后写入 str 的内容。请注意,在进行分配时,您也会泄漏所有分配的内存。

您需要将 names 定义为 char names[100][50] 并直接读入 fgets(names[count], 50 , 文件)。或者为每个成员分配内存(使用 malloc,就像您已经做的那样)并复制到其中(使用 strcpy)1


1 如果您有幸使用 POSIX 系统,strdup 可以在一次调用中完成这两项工作。

关于c - 虽然 C 中的循环分配没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40329979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com