gpt4 book ai didi

c - 如何将字符串输入到C中的数组中?

转载 作者:行者123 更新时间:2023-11-30 23:57:38 26 4
gpt4 key购买 nike

我试图从用户那里获取输入(字符串)并将它们存储在一个数组中。但是在我运行这段代码后,程序立即崩溃了。

#include <stdio.h>
int main() {
int i;
char *word[3];
for(i=0;i<3;i++)
{
printf(" Enter a word: ");
scanf("%s", &word[i]);
}
printf("%s ", word[0]);
return 0;
}

最佳答案

在这一行:

scanf("%s", &word[i]);

您需要确保 word[i]指向某处,并且有足够的空间来占据输入的字符串。自 word[i]char *指针,您需要在某个时候为此分配内存。否则,它只是一个不指向任何地方的悬空指针。

如果您想坚持使用 scanf() ,那么你可以预先用 malloc 分配一些空间.

malloc() allocates requested memory on the heap, then returns a void* pointer at the end.



您可以申请 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) reads a line from an input stream, and copies the bytes over to char *str, which must be given a size of n bytes as a threshold of space it can occupy.



fgets注意事项:
  • 附加 \n缓冲区末尾的字符。可以轻松移除。
  • 出错时,返回 NULL .如果没有读取字符,仍然返回 NULL在末尾。
  • 缓冲区必须静态声明为给定大小 n .
  • 读取指定的流。来自 stdinFILE * .

  • 这是一个如何使用它来读取来自 stdin 的输入行的示例。 :
    char buffer[100]; /* statically declared buffer */

    printf("Enter a string: ");
    fgets(buffer, 100, stdin); /* read line of input into buffer. Needs error checking */

    带注释的示例代码:
    #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

    关于c - 如何将字符串输入到C中的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41518039/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com