Я пытаюсь выполнить следующие действия в своем коде, который является реализацией текстовой сортировки в C.
- data [] содержит указатели на предложения, считанные из файла.
сделать копию j-го содержимого массива «data» и сохранить его в буфере строки char *.(Этот массив представляет собой массив указателей, созданных как const char ** data и распределенных неправильно следующим образом: data = malloc (sizeof (char *) * numlines))
Затем я пытаюсь выделить предложения в слова, используя пробел в качестве разделителя.
- Наконец, я пытаюсь сохранить указатели, возвращаемые strtok, в массиве указателей, инициализированных как char * tokenarray и malloc-ed как tokenarray = malloc (sizeof (char *)* numlines)).Вот код:
`
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#define MAXCHAR 150
#define COPYMAX 150
char inpstr[MAXCHAR]; //char array for the input string storage
char copyd[MAXCHAR]; // copy needed for some fxn
char *temp_bffr;
size_t buffsize;
int status;
char filename;
int numlines;
numlines = 5;
int i;
char *storedline;
FILE *fileo; //fopen pointer
const char **data;
int separate_words(char ** txtarray){
printf("separating\n");
char *token; //for strtok
char *tokenarray;
int j;
char *linebuffer = (char *) malloc(MAXCHAR); //malloc since we want to modify this copy?
tokenarray = malloc(sizeof(char *)*numlines);
for(j = 0; j<= numlines; j++){
//printf("Element[%d] = %d\n", j, data[j]);
strcpy(linebuffer, data[j]);
token = strtok(linebuffer, " ");
tokenarray[j] = token;
}
return 0;
}
int my_compare(const void *elem1, const void *elem2){
printf("comparing is hard");
//qsort????
return 0;
}
int main(){
fileo = fopen("short_alma.txt","r");
data = (char **)malloc(numlines * sizeof(char *));
//check stats from file
struct stat buffer;
if(fstat(status, &buffer) != 0){
printf("error: fstat()\n");
exit(1);
}
// temporary buffer
temp_bffr = malloc(sizeof(char)* (MAXCHAR +1));
i = 0;
//usefgets to start reading:
while(fgets(temp_bffr, MAXCHAR, fileo)){
//printf("temp_bffr is : \n");
//puts(temp_bffr);
//check sizeif line < MAX, save size and do realloc()
if(strlen(temp_bffr) < MAXCHAR){
buffsize = strlen(temp_bffr);
//malloc memory using buffer size before the string copy??? is this it???
data[i] = malloc(sizeof(char)*numlines);
strcpy(data[i], temp_bffr);
i++;
}
else{
printf("line has too many chars!");
}
}
separate_words(data); //separate the strings in our array
//return data;
return 0;
}
`