在这一行:
scanf("%s", &word[i]);
您需要确保word[i] 指向某个地方,并且有足够的空间来占用输入的字符串。由于word[i] 是char * 指针,因此您有时需要为此分配内存。否则,它只是一个不指向任何地方的悬空指针。
如果你想坚持scanf(),那么你可以预先分配一些空间malloc。
malloc() 在堆上分配请求的内存,然后在最后返回一个void* 指针。
您可以像这样在代码中应用malloc():
size_t malloc_size = 100;
for (i = 0; i < 3; i++) {
word[i] = malloc(malloc_size * sizeof(char)); /* allocates 100 bytes */
printf("Enter word: ");
scanf("%99s", word[i]); /* Use %99s to avoid overflow */
/* No need to include & address, since word[i] is already a char* pointer */
}
注意:必须检查malloc()的返回值,因为不成功时可以返回NULL。
此外,每当您使用malloc() 分配内存时,您必须在最后使用free 来释放请求的内存:
free(word[i]);
word[i] = NULL; /* safe to make sure pointer is no longer pointing anywhere */
另一种不用 scanf 的方法
更正确的读取字符串的方法应该是使用fgets。
char *fgets(char *str, int n, FILE *stream) 从输入流中读取一行,并将字节复制到char *str,它必须指定n 字节的大小作为它可以占用的空间阈值。
关于 fget 的注意事项:
- 在缓冲区末尾追加
\n 字符。可以轻松移除。
- 出错时返回
NULL。如果没有读取任何字符,最后仍然返回NULL。
- 缓冲区必须以给定大小静态声明
n。
- 读取指定的流。来自
stdin 或FILE *。
这是一个示例,说明如何使用它从stdin 读取一行输入:
char buffer[100]; /* statically declared buffer */
printf("Enter a string: ");
fgets(buffer, 100, stdin); /* read line of input into buffer. Needs error checking */
使用 cmets 的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMSTR 3
#define BUFFSIZE 100
int main(void) {
char *words[NUMSTR];
char buffer[BUFFSIZE];
size_t i, count = 0, slen; /* can replace size_t with int if you prefer */
/* loops only for three input strings */
for (i = 0; i < NUMSTR; i++) {
/* read input of one string, with error checking */
printf("Enter a word: ");
if (fgets(buffer, BUFFSIZE, stdin) == NULL) {
fprintf(stderr, "Error reading string into buffer.\n");
exit(EXIT_FAILURE);
}
/* removing newline from buffer, along with checking for overflow from buffer */
slen = strlen(buffer);
if (slen > 0) {
if (buffer[slen-1] == '\n') {
buffer[slen-1] = '\0';
} else {
printf("Exceeded buffer length of %d.\n", BUFFSIZE);
exit(EXIT_FAILURE);
}
}
/* checking if nothing was entered */
if (!*buffer) {
printf("No string entered.\n");
exit(EXIT_FAILURE);
}
/* allocate space for `words[i]` and null terminator */
words[count] = malloc(strlen(buffer)+1);
/* checking return of malloc, very good to do this */
if (!words[count]) {
printf("Cannot allocate memory for string.\n");
exit(EXIT_FAILURE);
}
/* if everything is fine, copy over into your array of pointers */
strcpy(words[count], buffer);
/* increment count, ready for next space in array */
count++;
}
/* reading input is finished, now time to print and free the strings */
printf("\nYour strings:\n");
for (i = 0; i < count; i++) {
printf("words[%zu] = %s\n", i, words[i]);
free(words[i]);
words[i] = NULL;
}
return 0;
}
示例输入:
Enter a word: Hello
Enter a word: World
Enter a word: Woohoo
输出:
Your strings:
words[0] = Hello
words[1] = World
words[2] = Woohoo