这些指针组成了一个指向 char 的数组,但它们并没有引用任何有效内存。
先为这些指针分配存储空间。
int main(void)
int pos;
char *labels[8];
for (pos=0; pos<8; ++pos) {
labels[pos]=malloc(LABELCAP);
scanf("%17s",labels[pos]);
}
for (pos=0; pos<8; ++pos) {
printf("%s\n",labels[pos]);
free(labels[pos]);
}
return 0;
}
另一种做法是
int main(void) {
int pos;
char labels[8][LABELCAP];
for (pos=0; pos<8; ++pos) {
scanf("%17s",labels[pos]);
}
for (pos=0; pos<8; ++pos) {
printf("%s\n",labels[pos]);
}
return 0;
}
从英语翻译·查看原文Those pointers form an array pointing to char, but they aren't referncing any valid memmory.
First allocate storage for those pointers:
int main(void)
int pos;
char *labels[8];
for (pos=0; pos<8; ++pos) {
labels[pos]=malloc(LABELCAP);
scanf("%17s",labels[pos]);
}
for (pos=0; pos<8; ++pos) {
printf("%s\n",labels[pos]);
free(labels[pos]);
}
return 0;
}
another option is
int main(void) {
int pos;
char labels[8][LABELCAP];
for (pos=0; pos<8; ++pos) {
scanf("%17s",labels[pos]);
}
for (pos=0; pos<8; ++pos) {
printf("%s\n",labels[pos]);
}
return 0;
}