c - 使用 strtok 后添加指向已建立指针数组的指针
问题描述
我正在尝试在我的代码中执行以下操作,这是 C 中 textsort 的实现。
- data[] 包含指向从文件中读取的句子的指针。
复制“数据”数组的第 j 个内容并将其存储在行缓冲区 char * 中。(此数组是一个指针数组,实例化为 const char **data 并按以下方式进行 malloc 编辑: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;
}
`
解决方案
推荐阅读
- javascript - 如何使用 JavaScript 或 jQuery 获取多个嵌套值?
- php - 如何在相关工厂laravel中传递变量
- csv - 如何在awk中将标记的文本组发送到CSV中的不同列?
- mysql - 在 mysql 5.7 中声明变量时出现错误 1064 (42000)
- c# - 如何在 Visual Studio 中加载 CPLEX 库?
- java - 使用级联将数据集分成块
- android - 片段中的布局仅显示在屏幕的一半上,但在活动中是正确的
- node.js - 在 SQL Server 原始查询 sequelize 中打印受影响的行
- android - Android Material Components 中新 ExtendedFloatingActionButton 的收缩和扩展功能不起作用
- android - 如何在警报对话框中将图像显示为消息?