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

标签 c arrays string pointers malloc

我正在编写一个读取字符列表的代码(使用重定向),但是我将字符存储到的字符串的大小为 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/

相关文章:

c - 将 CSV 文本文件中的值输入到数组中

c - 在Linux、C程序中触发系统调用的调用?

c - Return 语句不会在 c 中执行

java - 无论如何重新排列数组列表并删除打印行

javascript - 处理数组时可能发生 JavaScript 内存泄漏?

python - 在 python 中交换用户输入的元音

c - C中删除一个文件

c - 为什么 C 数组声明为 int arr[] 而不是 int []arr?

java - 在可能发生重叠的字符串数组中查找字符串的索引

python - 使用 python 将句子中的每个单词替换为单词索引