I want to read the following lines from STDIN and save the values in c:
A:2
B:3
C:AAAA1
C:AASC2
C:aade3
D:1
D:199
Here is my c program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
int main(int argc, char **argv)
{
char buf[BUFSIZ];
short a = 0;
short b = 0;
short anzb=0;
short anza=0;
char *c
short *d;
short i;
while (fgets(buf, BUFSIZ, stdin) != NULL)
{
if (buf[strlen(buf)-1] == '\n') {
char *isa = strstr(buf, "A:");
char *isb = strstr(buf, "B:");
char *isc = strstr(buf, "C:");
char *isd = strstr(buf, "D:");
if(isa){
char *sep = substring(isa,3,strlen(isa));
a = atoi(sep);
d = malloc(a * sizeof(short));
}else if(isb){
char *sep = substring(isb,3,strlen(isb));
b = atoi(sep);
c = malloc(b * sizeof(char));
}else if(isc){
char *sep = substring(isc,3,strlen(isc));
c[anzc] = sep;
anzc++;
}else if(isd){
char *sep = substring(isd,3,strlen(isd));
d[anzd] = sep;
anzd++;
}
}
}
printf("%i\n", a);
printf("%i\n", b);
for(i=0; i<=anzc-1;i++){
printf("%c", c[i]);
}
return 0;
}
I am new in c so i dont't have much knowledge about pointers and arrays so i hope you could help me.
After the values A: and B: are read and stored in a and b i could create my array for the lines of c and d. And i think here is my problem. I dont know how i could create an array at this time in my program. I tried with malloc and other things but there is my knowledge zu small for.
I only want to create an array at the time if i have read the values (sizes) for c and d (A and B).
And then i want to save the values in the array.
I hope you could help me to fix my code. I have tried much at this day but nothing worked and i am now very helpless.
EDIT:
New try where i get an segmentation fault 11:
else if(isb){
char *sep = substring(isb,8,strlen(isb));
b = atoi(sep);
c = malloc(b * sizeof(char*));
int i;
for (i = 0; i < subst; i++)
{
c[i] = malloc(13);
}
}else if(isc){
char *sep = substring(isc,8,strlen(isc));
strcpy(c[anzc], &buf[3]);
anzc++;
}