Divide a string into smaller parts & organize a structure (C-programming)
I am still learning C and I'm having some trouble figuring out how to handle this. Well, I have two structs:
struct myStruct {
...
struct myString *text[5];
...
} allStructs;
struct myString {
char part[100];
};
The objective is to have allStruct[n]
point to 5 different parts of a text divided into lines of 100 chars each. So I allocate the space:
allStructs = calloc(n, sizeof(allStructs));
Then, assume that I have a filled char text[500]
that I want to divide into 5 parts, and have allStructs[n].text[开发者_运维知识库n].part
point at a given part of the text. Can anyone help me with how I proceed?
Short answer: you can not with this because you have not consider the '\0' character to terminate each string.
Longer answer: Change structs like that to have more flexibility:
struct myStruct {
struct myString *text;
}
struct myString {
char *part;
}
The allocation should be:
struct myStruct *allStruct = calloc(n, sizeof(struct myStruct));
So you have a pointer/array on n struct myStruct.
Then initialize all members of allStruct;
for( i=0; i<n; ++i )
{
allStruct[i].text = calloc(5, sizeof(myString));
// Following for only needed if you want new strings by using the strncpy (see above)
for( y=0; y<5; ++y )
{
allSTruct[i].text[y].part = calloc(101, sizeof(char));
}
}
Now you have all vars initialized.
To copy your 500-chars long string into allStruct[n]:
for( i=0; i<5; i++ )
{
allStructs[n].text[i].part = &text[i*100]; // If you want to point on the existing string
// OR
strncpy(allStructs[n].text[i].part, &text[i*100], 100); // If you want to have new strings
// In all case, terminate the string with '\0'
allStructs[n].text[i].part[100] = '\0';
}
This should work.
Well, c strings are just an array of characters terminated by the null character ('\0'
). So you would want to iterate through the large text[500]
array putting 100 characters in each of the myString
parts. Bare in mind that since c strings are null terminated you will only be able to store 99 characters in char part[100]
.
Also if you wanted to only end a part on a white space character (space (' '
), new line ('\n'
) or tab ('\t'
)) you would have to find the nearest one to the 100 character limit and split the string up there.
allStructs
is an object of type struct myStruct
. You cannot "reassign" it with calloc()
.
Your object allStructs
has the member text
which is an array of 5 pointers.
You need to set those pointers to point at specific objects of the struct myString
type.
After you copy characters from char text[500]
to the various struct myString
objects, everything will work right.
pseudo code
struct myString part1;
struct myString part2;
struct myStruct allstructs;
allStructs.text[0] = &part1;
allStructs.text[1] = &part2;
strncpy(part1.part, text, 99);
part1.part[99] = '\0';
printf("part2: %s\n", allStructs.text[1].text);
Oh! And don't confuse allStructs
(ends with 's') with allStruct
(no 's')
精彩评论