【发布时间】:2019-04-11 09:52:50
【问题描述】:
在下面的代码中,我尝试为每个乐队获取乐队成员的数量。我已经尝试了很多东西,但没有任何效果。以下看起来应该但不是。
如果有人能指出我做错了什么,将不胜感激。
numMembers = sizeof(bands[0]) / sizeof(bands[0].members);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int i;
int j;
int numBands;
int numMembers;
int limit = 4;
struct band {
char name[10];
char *members[20];
};
const struct band bands[] =
{ {"Beatles", {"John", "George", "Paul", "Ringo", "Pete", "George"} },
{"Stones", {"Mick", "Keith", "Bill", "Charlie", "Brian"} },
{"Who", {"Pete", "Roger", "Keith", "John"} },
{"JHE", {"Jimmy", "Noel", "Mitch"} } };
numBands = sizeof(bands) / sizeof(bands[0]);
for ( i = 0; i < numBands; ++i ) {
printf ("%s\n", bands[i].name);
numMembers = sizeof(bands[0]) / sizeof(bands[0].members);
for ( j = 0; j < numMembers; ++j )
printf ("\t%s", bands[i].members[j]);
printf ("\n");
}
return 0;
}
【问题讨论】:
-
设计问题:为什么对乐队名称使用固定数组大小
char name[10],而对乐队成员使用字符指针?我希望像char *name; char *members[20];或char name[10]; char members[20][30]; -
第一行是语法错误
标签: c arrays pointers struct char