gpt4 book ai didi

c - 如何对 char 字符串/数组使用 malloc() 函数?

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:14 25 4
gpt4 key购买 nike

我正在编写一个读取字符列表的代码(使用重定向),但是我将字符存储到的字符串的大小为 41。字符数与数组,因此我需要使用 malloc() 以获得准确的数组大小。当我不使用 malloc 函数打印数组时,会打印符号和其他乱码以及字符串。我需要 malloc 字符串,这样就不会包含符号和乱码。

代码:

#include <stdio.h>
#include <stdlib.h>

int main() {

char c;
char r1[41];
int a = 0;

while(scanf("%c", &c) != EOF) {
if(c >= 'A' && c <= 'Z' || c == '[' || c == '.' || c == '!') {
r1[a] = c;
a++;
}
}

printf("\nThe string is: %s\n", r1);

return 0;
}

输出:

The string is TR[!.DFQ▒ ▒ ▒ 這

最佳答案

这里有几个混淆点。

  1. 您的代码打印乱码的原因不是固定长度与可变长度。切换到 malloc() 不会解决该问题。确保字符串末尾有空终止符 ('\0'):

    while(scanf("%c", &c) != EOF) {
    ...
    }

    r1[a] = '\0';
  2. 您的原始代码混合了数组和指针语法。对于单个字符串,您应该使用 char[]char* 但不能同时使用两者。

    对于固定大小的字符串,声明为:

    char string[40+1];

    对于可变长度的字符串,执行:

    char *string = malloc(length + 1);

    if (string == NULL) {
    fprintf(stderr, "malloc failed\n");
    exit(EXIT_FAILURE);
    }

    // memory allocation successful

关于c - 如何对 char 字符串/数组使用 malloc() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20107263/

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