Hi im new to the C language and I dont understant why im getting a Segmentation fault. Please help.
twi.c
insert
Code:
#include "twi.h"
/*char* readInput
*return the entire line
*/
char* getLine()
{
char *temp;
temp = (char*)malloc(sizeof(char[176]));
fgets(temp,176,stdin);
return temp;
}
/*void print
*accpet a struct twi
*Display info in twi
*/
void print(tData input)
{
printf("@%s %s %s %s\n", input->name, input->date, input->time, input->msg);
}
/*char* findMsg
*accept char*
*return char* the msg in the string which is 3 isspace away.
*/
char* findMsg(char *input)
{
char *p;
p = input;
int count = 0;
while(isspace(*p) || count != 3)
{
if(isspace (*p))
count++;
++p;
};
char *p2 = input;
int run;
run = (p-input);
while(run!=0)
{
*p2++;
run--;
}
return p2;
}
/*int make
*create a struct using char* provide
*return int for checking
*/
int make(tData temp, char* input)
{
int check;
//create temporary variable
char nameSize[15];
char timeSize[10];
char dateSize[10];
check = sscanf(input, "%s %s %s", nameSize,dateSize,timeSize);
//allocate memory depending on length of char
temp->name = (char*)malloc(sizeof(strlen(nameSize)));
temp->date = (char*)malloc(sizeof(strlen(dateSize)));
temp->time = (char*)malloc(sizeof(strlen(timeSize)));
temp->msg = (char*)malloc(sizeof(strlen(findMsg(input))));
//copying into struct
strcpy(temp->name, nameSize);
strcpy(temp->date, dateSize);
strcpy(temp->time, timeSize);
strcpy(temp->msg, findMsg(input));
// printf("%s %s %s %s",temp->name,temp->date,temp->time, temp->msg);
if(check == 3)
return check;
else
return 0;
}
p3.c
insert
Code:
#include <stdio.h>
#include <stdlib.h>
#include "twi.h"
main()
{
tData t[100];
int i = 0;
char* str;
int check = 3;
t[0] = (struct twi*)malloc(sizeof(char[300]));
str = getLine();
while(make(t[i],str) == 3)
{
str = getLine();
i++;
// t[i] = (struct twi*)malloc(sizeof(struct twi));
}
int x;
for(x = 0; x < i-1; x++)
print(t[x]);
}