简短的回答:您不能这样做,因为您没有考虑使用 '\0' 字符来终止每个字符串。
更长的答案:更改这样的结构以获得更大的灵活性:
struct myStruct {
struct myString *text;
}
struct myString {
char *part;
}
分配应该是:
struct myStruct *allStruct = calloc(n, sizeof(struct myStruct));
所以你在 n struct myStruct 上有一个指针/数组。
然后初始化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));
}
}
现在你已经初始化了所有的变量。
将 500 个字符的长字符串复制到 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';
}
这应该有效。