C中的字符串数组操作
Array of Strings Manipulation in C
迭代可变字符串数组的最佳方法是什么?例如:
struct Book{
char chapter_names[20][50];
int chapters;
...}
int main(){
struct Book Redwall;
strcpy(*chapter_names, "The Wall");
strcpy(*(++chapter_names), "The Grove");
printf("Chapter 1: %s", chapter_names[0]);
printf("Chapter 2: %s", chapter_names[1]);
return 0;
}
我希望它的输出是:
Chapter 1: The Wall
Chapter 2: The Grove
此代码导致
error: lvalue is required as increment operand
您不能在结构中的数组上使用像这样的递增运算符。您可能正在寻找如下代码:
struct Book{
char chapter_names[20][50];
int chapters;
};
int main(){
struct Book Redwall;
strcpy(*(Redwall.chapter_names), "The Wall");
strcpy(*(Redwall.chapter_names+1), "The Grove");
printf("Chapter 1: %s\n", Redwall.chapter_names[0]);
printf("Chapter 2: %s\n", Redwall.chapter_names[1]);
return 0;
}
既然你有一个 int 来跟踪你有多少章节名称,你应该使用它。
Redwall.chapters = 0; // Make sure it's initialised first
strcpy(Redwall.chapter_names[Redwall.chapters++], "The Wall");
strcpy(Redwall.chapter_names[Redwall.chapters++], "The Grove");
然后您可以使用 for 循环循环遍历它们中的每一个。
for(i=0;i<Redwall.chapters;i++) {
printf("Chapter %d: %s", i+1, Redwall.chapter_names[i]);
}
迭代可变字符串数组的最佳方法是什么?例如:
struct Book{
char chapter_names[20][50];
int chapters;
...}
int main(){
struct Book Redwall;
strcpy(*chapter_names, "The Wall");
strcpy(*(++chapter_names), "The Grove");
printf("Chapter 1: %s", chapter_names[0]);
printf("Chapter 2: %s", chapter_names[1]);
return 0;
}
我希望它的输出是:
Chapter 1: The Wall
Chapter 2: The Grove
此代码导致
error: lvalue is required as increment operand
您不能在结构中的数组上使用像这样的递增运算符。您可能正在寻找如下代码:
struct Book{
char chapter_names[20][50];
int chapters;
};
int main(){
struct Book Redwall;
strcpy(*(Redwall.chapter_names), "The Wall");
strcpy(*(Redwall.chapter_names+1), "The Grove");
printf("Chapter 1: %s\n", Redwall.chapter_names[0]);
printf("Chapter 2: %s\n", Redwall.chapter_names[1]);
return 0;
}
既然你有一个 int 来跟踪你有多少章节名称,你应该使用它。
Redwall.chapters = 0; // Make sure it's initialised first
strcpy(Redwall.chapter_names[Redwall.chapters++], "The Wall");
strcpy(Redwall.chapter_names[Redwall.chapters++], "The Grove");
然后您可以使用 for 循环循环遍历它们中的每一个。
for(i=0;i<Redwall.chapters;i++) {
printf("Chapter %d: %s", i+1, Redwall.chapter_names[i]);
}