【发布时间】:2014-09-14 02:31:14
【问题描述】:
我打算用 C 语言做一个关于动态内存分配的书本练习。程序要我做以下事情
-read a file and open a file from stdin, for example ./program < input.txt > output.txt
-store each line by dynamically creating an array of strings
*assume and allocate enough space to store 5 lines of type char*
when this turns out to insufficient double the amount of space to store more/*realloc?*/
*when allocatingspace to store line,allocate only enough memory to store particular line
-print lines to screen in reverse order
-print number of lines to screen
-print total characters to screen
(we can assume each line can be stored in 1000 bytes)
我试图计划我的方法来做到这一点,并希望得到一些意见。我是动态内存分配的新手,所以如果我屠夫但我已经阅读过它,请原谅我。以下将是我的伪代码方法和问题。假设我们有带行的文件输入
hello world
store these lines
but only enough memory to store these particular lines
then print out these lines in reverse
make sure to keep track of the line count,and character count
this is a 6th line so double the space of the array to store 10 lines
我的伪代码破折号表示一般指令,*更详细一些
-read file in from stdin
begin index count for the string_array
/*we can assume line will fit into 1000 bytes*/
buffer[1000]
/*allocate memory to store 5 adresses of strings*/
char** string_array = malloc(5 * sizeof(char))
/*begin reading file*/
while(fgets(buffer,sizeof(buffer),stdin != NULL))
-store each line in buffer into the array
/*allocate only enough space to store the particular line,not sure how to do this but..*/
string_array[index] = malloc(strlen(buffer) * sizeof(char)) /*afraid buffer will be 1000 like intialized?*/
/*add characters of line to character sum and add the line to linesum*/
charactersum = charactersum + strlen(buffer)
linesum = linesum + 1
/*fill the array index with each line string*/
strcpy(string_array[index],buffer
increment index
我不知道的一件事是如何为 string_array 重新分配空间,因为最终它将需要更多空间来存储 5 个地址。我在想。。
string_array = realloc(string_array, 2*sizeof(string_array)
但是我如何检查我的数组是否没有更多空间来存储字符串地址以便重新分配以及我将它放在哪里?这种方法可行吗?我希望我正确使用 malloc 和 realloc 没有匹配错误,因为我遇到了这些问题。打印,我可以做得很好,但我更关心正确满足动态分配要求并正确构建数组
【问题讨论】:
-
提示:
2*sizeof(string_array)不会像你想象的那样做。 -
我认为这是不正确的,我必须在其中的某处包含 char 吗?
-
它在多个层面上都是错误的。首先它是指针的大小,而不是原始分配的基础大小的大小。其次,它的大小错误的类型。
string_array指向的是char*, notchar**` 的动态序列。我认为你只需要在动态分配一章中复习一下。它很容易成为新 C 程序员最难掌握的东西。 -
当使用
char** string_array创建时,变量string_array将始终衰减为简单的char *,(通常在32 位机器上为4 字节,在64 位机器上为8 字节),无论分配了多少内存。所以sizeof(string_array)将返回 4 或 8。这不是你需要的。 -
while(fgets(buffer,sizeof(buffer),stdin != NULL))-->while(fgets(buffer,sizeof(buffer),stdin) != NULL)