Я пытаюсь разбить строку каждые X количество символов, а затем сохранить каждую строку в массиве структур. Тем не менее, мне интересно, какой будет короткий и эффективный способ сделать это. Я думал, что, возможно, я мог бы использовать sscanf
, но не очень уверен, как это сделать. Любая помощь будет оценена. До сих пор у меня есть:C - split/store string длины X в массив структур
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st {char *str;};
int main()
{
struct st **mystruct;
char tmp[] = "For configuration options (arch/xxx/config.in, and all the Config.in files),somewhat different indentation is used.";
size_t max = 20, j = 0; // max length of string
size_t alloc = strlen(tmp)/max + 1;
mystruct = malloc(alloc * sizeof *mystruct);
for (j = 0; j < alloc; j++)
mystruct[j] = malloc(sizeof *mystruct[j]);
const char *ptr = tmp;
char field [ max ];
int n;
while (*ptr != '\0') {
int line = sscanf(ptr, "%s", field, &n); // not sure how to use max in here
mystruct[j]->str = field;
field[0]='\0';
if (line == 1)
ptr += n;
if (n != max)
break;
++ptr;
++j;
}
return 0;
}
Так что, когда я итерация по моей структуре, я могу получить что-то вроде:
For configuration op
tions (arch/xxx/conf
ig.in, and all the C
onfig.in files),some
what different inden
tation is used.
Вы могли бы разработать немного больше, когда говорите, используя strncpy? спасибо – demit1501