相关疑难解决方法(0)

我是否施放了malloc的结果?

这个问题,有人建议意见,我应该不会投的结果malloc,即

int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

而不是:

int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?

c malloc casting

2318
推荐指数
27
解决办法
22万
查看次数

学习C,会欣赏有关此解决方案工作原理的信息

这是我用C编写的第一件事,所以请随意指出它的所有缺陷.:)我的问题是这样的:如果我按照我认为最干净的方式编写程序,我会得到一个破碎的程序:

#include <sys/queue.h> 

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/* Removed prototypes and non related code for brevity */

int
main()
{
    char    *cmd = NULL; 
    unsigned int acct = 0; 
    int amount = 0; 
    int done = 0; 

    while (done==0) {
        scanf ("%s %u %i", cmd, &acct, &amount);

        if (strcmp (cmd, "exit") == 0)
            done = 1;
        else if ((strcmp (cmd, "dep") == 0) || (strcmp (cmd, "deb") == 0))
            debit (acct, amount);
        else if ((strcmp (cmd, "wd") == …
Run Code Online (Sandbox Code Playgroud)

c segmentation-fault

7
推荐指数
3
解决办法
451
查看次数

将 fgets 与 realloc() 结合使用

我正在尝试创建一个函数来从文本文件中读取一行,fgets()并将其存储在动态分配的 char* 中,malloc()但我不确定如何使用realloc(),因为我不知道这一行的长度文本,并且不想只是猜测该行可能的最大大小的幻数。

#include "stdio.h"
#include "stdlib.h"
#define INIT_SIZE 50

void get_line (char* filename)

    char* text;
    FILE* file = fopen(filename,"r");

    text = malloc(sizeof(char) * INIT_SIZE);

    fgets(text, INIT_SIZE, file);

    //How do I realloc memory here if the text array is full but fgets
    //has not reach an EOF or \n yet.

    printf(The text was %s\n", text);

    free(text);

int main(int argc, char *argv[]) {
    get_line(argv[1]);
}
Run Code Online (Sandbox Code Playgroud)

我计划用文本行做其他事情,但为了保持简单,我刚刚打印了它,然后释放了内存。

另外: main 函数是通过使用文件名作为第一个命令行参数来启动的。

c malloc realloc

3
推荐指数
1
解决办法
2729
查看次数

标签 统计

c ×3

malloc ×2

casting ×1

realloc ×1

segmentation-fault ×1