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.
vcsaschar *vcs;(a single char pointer) but try to use it as achar*array inread(an array ofchar*)