【问题标题】:Realloc and sscanf into a functionrealloc 和 sscanf 变成一个函数
【发布时间】:2014-01-31 14:28:02
【问题描述】:

我有一个文件有num 行:每一行都包含一个数字。我想将每个数字保存到一个向量*vet。为什么这段代码不起作用?

Segmentation fault (core dumped)

我认为错误是sscanf in save_numbers function,但我不知道为什么。

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

/* This function allocate memory
and save numbers into a vector */
int save_numbers (int **vet, int *num)
{
    FILE *fin;
    int i = 0;
    char buff[10];

    if ( !(fin = fopen("numbers.dat", "r")) )
        return 1;

    while ( fgets(buff, sizeof(buff), fin) )
    {
        *vet = (int *) realloc (*vet, (i+1) * sizeof(int) );
        sscanf (buff, "%d", vet[i]);
        i++;
    }

    *num = i;

    return fclose(fin);
}

int main ()
{
    int i, num, *vet = NULL;    

    if ( save_numbers(&vet, &num) )
    {
        perror("numbers.dat");
        exit(1);
    }

    /* print test */
    for (i=0; i<num; i++)
        printf ("%d ", vet[i]);
    printf("\n");

    free(vet);

    return 0;
}

此处的文件示例:http://pastebin.com/uCa708L0

【问题讨论】:

  • @A Person 但是如果我想用int *vet 而不是int vect[MAX_NUM_OF_NUMS] 我能做什么?我使用realloc 分配内存的确切大小以包含数字。
  • 但是为什么呢? *vet = (int *) realloc (*vet, (i+1) * sizeof(int) ); 不正确?
  • 次要:建议char buff[10]; 使用更大的尺寸,至少char buff[13]; 用于“-2147483648\n”或增长2 倍。
  • @chux.or 2x that for growth.是什么意思

标签: c file function malloc realloc


【解决方案1】:

改变

sscanf (buff, "%d", vet[i]);//vet : int **

sscanf (buff, "%d", &(*vet)[i]);

【讨论】:

  • 有效!非常感谢!请问一般的代码好不好?
猜你喜欢
  • 2014-01-31
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 2011-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多