gpt4 book ai didi

c - 初学者C : Dynamic memory allocation

转载 作者:行者123 更新时间:2023-11-30 17:28:04 27 4
gpt4 key购买 nike

从 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com