c - 初学者C : Dynamic memory allocation

标签 c memory

从 Java 切换到 C,我在掌握内存管理方面遇到了一些麻烦

假设我有一个函数 *check_malloc,其行为如下:

// Checks if malloc() succeeds.
void *check_malloc(size_t amount){

  void *tpt;

  /* Allocates a memory block in amount bytes. */
  tpt = malloc( amount );

  /* Checks if it was successful. */
  if ( tpt == NULL ){
      fprintf(stderr, "No memory of %lu bytes\n", amount);
       exit(1); 
  }

  return tpt;
}

我还有以下变量可供使用:

FILE *f = fopen("abc.txt", "r");  // Pointer to a file with "mynameisbob" on the first line and 
                                  //                        "123456789"   on the second line 
char *pname;                      // Pointer to a string for storing the name

}

我的目标是使用*check_malloc动态分配内存,以便*pname指向的String正好是正确的大小存储“mynamisbob”,这是文本文件第一行中唯一的内容。

这是我的(失败的)尝试:

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

FILE *f = fopen("abc.txt", "r");  // A file with "mynameisbob" on the first line and 
                                  //             "123456789"   on the second line 

char *pname;                      // Pointer to a string for storing the name

char currentline[150];            // Char array for storing current line of file

while(!feof(f)){
    fgets(currentline,100,f);
    pname = &currentline; 
}

但我知道这可能不是解决这个问题的方法,因为我需要使用我很好的 check_malloc* 函数。

此外,在我的实际文本文件中,第一行的名称前面有一个“<”符号。但我只想让 *pname 指向一个字符串“mynameisbob”,而不带“<”符号。现在这并不重要,它只是对我来说是一种强化,我知道我不能只是将指针设置为直接指向 currentline

谁能帮我修正一下我对这个问题的想法吗?多谢。

最佳答案

在 C 中,您需要复制字符,而不是“字符串”(它们只是指针)。查看 strcpy() 和 strlen()。使用 strlen() 确定 fgets 已读取的行实际长度,然后使用 malloc() 准确分配该行(为 0 加 1)。然后使用 strcpy() 复制字符。

关于c - 初学者C : Dynamic memory allocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26150981/

相关文章:

c - 如何在 32 位中引发浮点错误

c - 在 C 中使用带指针的模运算符

c - GCC 和 Clang 解析器真的是手写的吗?

c - 可以将不同的数据类型存储在 C 中相同的分配内存中吗?

ios - 所有 iPad 版本的内存警告阈值

c++ - 在 C++ 中指向同一个内存块的数组?

c - 将 int 数组快速转换为 fp 以进行音频处理

javascript - 谷歌浏览器堆快照(闭包),(数组),(系统),(编译代码)在程序员控制下?

Ruby 符号不是垃圾收集的!?那么,使用String不是更好吗?

java - Android/Java - 通过在分配之前检测剩余的可用 RAM 来防止 OutOfMemoryError