我正在编写一个读取字符列表的代码(使用重定向),但是我将字符存储到的字符串的大小为 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▒ ▒ ▒ 這
这里有几个混淆点。
您的代码打印乱码的原因不是固定长度与可变长度。切换到 malloc() 不会解决该问题。确保字符串末尾有空终止符 ('\0'
):
while(scanf("%c", &c) != EOF) {
...
}
r1[a] = '\0';
您的原始代码混合了数组和指针语法。对于单个字符串,您应该使用 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
我是一名优秀的程序员,十分优秀!