c - 动态内存分配实践

标签 c arrays string dynamic

我想用 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,没有匹配错误,因为我在这些方面遇到了麻烦。打印,我可以做得很好,但我更关心正确满足动态分配要求并正确构建数组

最佳答案

关于您的陈述:
打印,我可以做得很好,但我更关心正确满足动态分配要求并正确构建数组

以下是创建、修改和释放内存的一些步骤
char **string_array={0};//将成为“字符串”数组

注意: C 并没有真正的 string 类型,但是当 char 数组以 NULL 字符 (\0),通常称为C 字符串

1) 确定字符串的数量以及每个字符串的最大长度。为了简单说明,请使用:

#define NUM_STRINGS 10
#define MAX_STR_LEN 10  

2)为每个字符串创建指针(实际上只是创建 NUM_STRINGS 个 char *)

string_array=malloc(NUM_STRINGS * sizeof(char *));//creates 10 char *  

现在你有 *string_array[0] 到 *string_array[9],每个都有
内存中的位置,但没有内存空间。 (差别很大)

3) 为每个 char * 分配内存空间,从而创建 char 数组

for(i=0;i<NUM_STRINGS;i++)
{
    string_array[i]=malloc(MAX_STR_LEN +1);//+1 for null terminator
                                           //note: this could have also been 
                                           //...(MAX_STR_LEN * sizeof(char) +1)
                                           //but because sizeof(char) == 1, it is equivalent
}  

4) 对于 string_array 的内存重新分配,您可以再次使用#define:

for(i=0;i<NUM_STRINGS;i++)
{
    string_array[i] = realloc(string_array, 2*MAX_STR_LEN +1);
}

注意:
realloc 也可以用于增加字符串的数量,这里只是
用于更改每个现有字符串的长度

5) 最后,当使用完以这种方式创建的任何变量时,它的内存位于
而不是堆栈,并且必须被释放。

for(i=0;i<NUM_STRINGS;i++)
{
    free(string_array[i]);
}
free(string_array);    

总而言之这里是上面讨论的所有内容(除了realloc)都包含在两个
函数创建字符串数组,然后释放它们:

//Create string arrays
char ** allocMemory(char ** a, int numStrings, int maxStrLen)
{
    int i;
    a = calloc(sizeof(char*)*(numStrings), sizeof(char*));
    for(i=0;i<numStrings; i++)
    {
      a[i] = calloc(sizeof(char)*maxStrLen + 1, sizeof(char));
    }
    return a;
}
//free string arrays
void freeMemory(char ** a, int numStrings)
{
    int i;
    for(i=0;i<numStrings; i++)
        if(a[i]) free(a[i]);
    free(a);
}  

使用示例:

int main(void)
{
    char **str=0;
    //create array pointers and space for desired number of strings:
    str = allocMemory(str, NUM_STRINGS, MAX_STR_LEN);//create space for NUM_STRINGS strings, 
                                                     //each with space for MAX_STR_LEN + 1 characters 
                                                     //(+1 for NULL);  
    //use strings...

    //when done using:
    freeMemory(str, NUM_STRINGS);
    return 0;
}

关于c - 动态内存分配实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901464/

相关文章:

c - 指针处的值仅在使用时才会更新

c - 使用 for 循环将字符存储到字符串中?

python查找文件中正则表达式匹配次数最多的部分

c - 使用 dlmalloc 的段错误

c - Linux 上 C 语言的 Dirent 迭代

php排序数组和排名特定字段

javascript - 遍历 FileList 声明

javascript - 在 Angular 中将对象数组传递给 POST

在C中复制字符串的结尾

mysql - 将数百万行重新格式化为 CSV 的最快方法