在C中加载长度为0的数组

时间:2017-04-05 08:34:59

标签: c arrays function save load

每当加载函数遇到数组长度为0的情况时,我都会一直收到此错误。我非常感谢您解决此问题的任何帮助!收到的代码和错误分别是:

/*
Save the entire array ia into a file called 'filename' in a JSON
text file array file format that can be loaded by
intarr_load_json(). Returns zero on success, or a non-zero error
code on failure. Arrays of length 0 should produce an output file
containing an empty array.

The JSON output should be human-readable.

Examples:

The following line is a valid JSON array:
 [ 100, 200, 300 ]

The following lines are a valid JSON array:
[
100,
200,
300
]
*/ 

int intarr_save_json( intarr_t* ia, const char* filename )
{
    if (ia == NULL)  {
        return 1;
    }
    int *arr=ia->data;
    if (arr == NULL) { 
        return 1;
    }
    int n=ia->len;
    if (n == 0 ) {
        return 0;
    }
    int i;
    FILE *p;
    p=fopen(filename,"w");

    if(p!=NULL)
    {
        fprintf(p,"[\n");
        for(i=0;i<n;i++)
        {
            if(i!=n-1)
            {
                fprintf(p," %d,\n",arr[i]);
            }
            else
            {
                fprintf(p," %d\n",arr[i]);
            }
        }
        fprintf(p,"]");
        fclose(p);
        return 0;
    }
    return 1;
}

/*
Load a new array from the file called 'filename', that was
previously saved using intarr_save(). The file may contain an array
of length 0. Returns a pointer to a newly-allocated intarr_t on
success (even if that array has length 0), or NULL on failure.
*/

intarr_t* intarr_load_json( const char* filename ){ 
    if (filename == NULL) { 
        return NULL;
    }
    FILE* f = fopen(filename, "r");
    if (f == NULL) { 
        return NULL;
    }

    intarr_t* loaded = intarr_create(0);

    char c;
    fscanf(f, "%c ", &c);

    int value;
    while (fscanf(f, "%d, ", &value)) {
        intarr_push(loaded, value);
    }
    if (fscanf(f, "%d ", &value)){
        intarr_push(loaded, value);
    }

    fclose(f);
    return loaded;
}

收到错误:

Saving array len 0: intarr_save_json( 0x1277010, "saved_array.0" )
    Loading array intarr_load_json( "saved_array.0" )
    Error: intarr_load_json() returned NULL pointer.

0 个答案:

没有答案