所以我正在为学校做作业,并编写了以下代码的变体:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
// This program takes an input of strings and prints them out with a new line separating each one.
int main() {
char *WordArray[MAX]; //initializing variables
int i = 0;
int count = 0;
printf("enter up to 100 words, that are 20 characters maximum \n");
for (i = 0; i <100; i++){ //runs while there's less than 100 inputs
char Array[1];
scanf("%s",Array); //stores string in the array
if (strcmp(Array, "STOP") == 0) { //compares the string with stop, and if it is, it breaks out of the loop
break;
}
WordArray[i]=Array; //stores the string in the pointer array
}
printf("The output is\n");
for (count = 0; count<i; count++){ //counts up to the amount of words stored
printf("%s\n",WordArray[count]); //outputs each pointer string
}
}
,我注意到输出正在打印“ STOP”,而不是存储的值。任何人都对为什么和/或如何解决它有任何答案?我知道其中一种方法是切换到2D数组而不是使用指针,但是我仍然对为什么这样的程序行不通感到困惑。
答案 0 :(得分:1)
您的char Array[1];
不够大,无法存储空字符串。同样,当它起作用时,每个指针都将指向相同的字符串,这将是您输入的最后一个条目。这会在有评论的地方进行一些更正。
#include <stdio.h>
#include <stdlib.h> // instead of ctype.h
#include <string.h>
#define MAX 100
// This program takes an input of strings and prints them out with a new line separating each one.
int main() {
char *WordArray[MAX];
int i = 0;
int count = 0;
printf("enter up to 100 words, that are 20 characters maximum \n");
for (i = 0; i <100; i++){
char Array[21]; // increase size of array
scanf("%20s",Array); // limit entry length
if (strcmp(Array, "STOP") == 0) {
break;
}
WordArray[i] = strdup(Array); // allocate memory for and copy string
}
printf("The output is\n");
for (count = 0; count<i; count++){
printf("%s\n",WordArray[count]);
}
// free each string's memory
for (count = 0; count<i; count++){
free(WordArray[count]);
}
}
程序输出:
enter up to 100 words, that are 20 characters maximum one two three STOP The output is one two three
char Array[1]
之外,您的代码还包含另一个未定义的行为,这是您取消引用了char *WordArray[MAX];
中存储的指针。 Array
的 scope 处于for
循环内,并且从理论上讲,在循环完成后不再存在,因此您存储的指针无效。在这里,输入的单词与strdup
重复,因此不适用。