【发布时间】:2011-03-15 17:56:31
【问题描述】:
我正在尝试从 python 背景自学 C。我目前的小问题是尝试减少对数组长度等事情的硬编码,并根据输入动态分配内存。
我编写了以下程序。我希望社区提供建议以通过以下方式对其进行修改:
1.) 使 first 和 last Name 元素可变长度。目前它们的长度被硬编码为MAX_NAME_LENGTH。这将涉及更改 Names structdeclaration 以及我为其元素分配值的方式。
2.) 奖励:想办法逐步向name_list 数组添加新元素,而无需事先确定其长度。基本上使它成为一个可扩展的列表。
/* namelist.c
Loads up a list of names from a file to then do something with them.
*/
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#define DATAFILE "name_list.txt"
#define DATAFILE_FORMAT "%[^,]%*c%[^\n]%*c"
#define MAX_NAME_LENGTH 100
typedef struct {
char first[MAX_NAME_LENGTH];
char last[MAX_NAME_LENGTH];
} Name;
int main() {
FILE *fp = fopen(DATAFILE, "r");
// Get the number of names in DATAFILE at runtime.
Name aName;
int lc = 0;
while ((fscanf(fp, DATAFILE_FORMAT, aName.last, aName.first))!=EOF) lc++;
Name *name_list[lc];
// Now actually pull the data out of the file
rewind(fp);
int n = 0;
while ((fscanf(fp, DATAFILE_FORMAT, aName.last, aName.first))!=EOF)
{
Name *newName = malloc(sizeof(Name));
if (newName == NULL) {
puts("Warning: Was not able to allocate memory for ``Name`` ``newName``on the heap.");
}
memcpy(newName, &aName, sizeof(Name));
name_list[n] = newName;
n++;
}
int i = 1;
for (--n; n >= 0; n--, i++) {
printf("%d: %s %s\n", i, name_list[n]->first, name_list[n]->last);
free(name_list[n]);
name_list[n] = NULL;
}
fclose(fp);
return 0;
}
name_list.txt的示例内容:
Washington,George
Adams,John
Jefferson,Thomas
Madison,James
更新 1:
我已经按照@Williham 的建议实现了一个链表和一些辅助函数,结果如下。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DATAFILE "name_list.txt"
#define MAX_NAME_LENGTH 30
#define DATAFILE_FORMAT "%29[^,]%*c%29[^\n]%*c"
static const int INPUT_BUFFER_SIZE_DEFAULT = sizeof(char) * MAX_NAME_LENGTH;
typedef struct _Name Name;
struct _Name {
char *first;
char *last;
Name *next;
};
int get_charcount(char *str);
Name * create_name_list(char *filename);
void print_name_list(Name *name);
void free_name_list (Name *name);
int main() {
// Read a list of names into memory and
// return the head of the linked list.
Name *head = create_name_list(DATAFILE);
// Now do something with all this data.
print_name_list(head);
// If you love something, let it go.
free_name_list(head);
head = NULL;
return 0;
}
int get_charcount (char *str)
{
int input_length = 1;
while (str[input_length] != '\0')
{
input_length++;
}
return input_length;
}
Name * create_name_list(char *filename)
{
FILE *fp = fopen(DATAFILE, "r");
char *first_input_buffer = malloc(INPUT_BUFFER_SIZE_DEFAULT);
char *last_input_buffer = malloc(INPUT_BUFFER_SIZE_DEFAULT);
Name *firstNamePtr;
Name *previousNamePtr;
while ((fscanf(fp, DATAFILE_FORMAT, last_input_buffer, first_input_buffer))!=EOF)
{
Name *newNamePtr = malloc(sizeof(Name));
if (previousNamePtr)
{
previousNamePtr->next = newNamePtr;
previousNamePtr = newNamePtr;
}
else
{
firstNamePtr = previousNamePtr = newNamePtr;
}
char *temp_buffer = malloc(get_charcount(first_input_buffer));
strcpy(temp_buffer, first_input_buffer);
newNamePtr->first = malloc(get_charcount(first_input_buffer));
strcpy(newNamePtr->first, temp_buffer);
realloc(temp_buffer, get_charcount(last_input_buffer));
strcpy(temp_buffer, last_input_buffer);
newNamePtr->last = malloc(get_charcount(last_input_buffer));
strcpy(newNamePtr->last, temp_buffer);
free(temp_buffer);
temp_buffer = NULL;
}
previousNamePtr->next = NULL;
previousNamePtr = NULL;
free(first_input_buffer);
free(last_input_buffer);
first_input_buffer = NULL;
last_input_buffer = NULL;
fclose(fp);
return firstNamePtr;
}
void print_name_list (Name *name)
{
static int first_iteration = 1;
if (first_iteration)
{
printf("\nList of Names\n");
printf("=============\n");
first_iteration--;
}
printf("%s %s\n",name->first, name->last);
if (name->next)
print_name_list(name->next);
else
printf("\n");
}
void free_name_list (Name *name)
{
if (name->next)
free_name_list(name->next);
free(name->first);
free(name->last);
name->first = NULL;
name->last = NULL;
name->next = NULL;
free(name);
name = NULL;
}
【问题讨论】:
-
@Alok:如果是作业,那是非常隐蔽且礼貌的作业要求。
-
@Alok 这是我给自己布置的作业。我从 MIT 的 Practical Programming in C (ocw.mit.edu/courses/electrical-engineering-and-computer-science/…) 开始的问题略有不同。我喜欢从列表中读取数据的前提,因为它在 python 中非常熟悉,所以我在问题中添加了一些额外的位,这些位在 python 使微不足道的类似问题中很熟悉。我自己研究它,直到我不完全确定如何继续,谷歌搜索,阅读并在这里询问。
标签: c dynamic arrays struct malloc