从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动态分配内存,以使String指向的*pname只是存储“ 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:动态内存分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26150981/

10-12 15:01
查看更多