简体   繁体   中英

Dynamic memory allocation issue

I've been trying to make this C program to work for some time, but I'm still having some great trouble with the memory allocation. The main point of this piece of work is that it's supposed to read a string from the first line of a file, then 2 numbers from the 2nd line and then 3 column vectors each having thrice as many members as the difference between the 2 read numbers.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void read(char **banda, int *s, int *sf, int **vs, char **vcs, char **vd)
{
    FILE *fin;
    int i;
    fin = fopen("date.in", "r");
    *banda = (char*)malloc(50*sizeof(char));
    fgets(*banda, 50, fin);
    fscanf(fin, "%d", s);
    fscanf(fin, "%d", sf);
    fseek( fin, 1, SEEK_CUR );
    int l = 3* ( (*s)-(*sf) );
    *vcs = (char*) malloc( l * sizeof(char) );
    *vd = (char*) malloc( l *sizeof(char) );
    *vs = (int*) malloc( l * sizeof(int) );
    for( i = 0; i< l ; i++ )
    {
        fscanf(fin, "%d", vs[i]);
        fscanf(fin, " %c", vcs[i]);
        fscanf(fin, " %c", vd[i]);
        fseek( fin, 1 , SEEK_CUR );
    }
    fclose(fin);
}

int main()
{
    char *banda;
    int i;
    int s, sf;
    char *vcs;
    char *vd;
    int *vs;
    read(&banda, &s, &sf, &vs, &vcs, &vd);
    for( i = 0; i < strlen(banda) ; i++ )
    {
        printf("%c", banda[i]);
    }
    printf("%d %d\n", s, sf);
    for( i = 0; i < 3*(s-sf) ; i++ )
    {
        printf("%d %c %c\n", vs[i], vcs[i], vd[i]);
    }

}

Example input: 
Helen
2 1
1 H A
2 B C
5 K I

However, I can't seem to allocate the memory for it. If I go past i=0(aka the first position in the arrays) the program shows me a neat "Segmentation fault". However, if I only go and write in the array ONE value for each, it doesn't crash. There's something I'm seriously missing and I just can't figure it out.

The problem is here:

fscanf(fin, "%d", vs[i]);
fscanf(fin, " %c", vcs[i]);
fscanf(fin, " %c", vd[i]);

The variables vs , vcs , and vd are pointers to arrays. Here, you're treating them as arrays of pointers. You need to first dereference the pointer, then get the array element you want to write to, then take its address:

fscanf(fin, "%d", &(*vs)[i]);
fscanf(fin, " %c", &(*vcs)[i]);
fscanf(fin, " %c", &(*vd)[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM