<分区>
我正在使用我安装的 gcc 编译器,它是从我的 cmd 运行的(在编辑器可视代码中编写)&为了调试我还安装了 visual studio。
这是我的第二个学期,我刚刚学习了 malloc
/calloc
等。
所以行:
ch_pointer = (char *)malloc(length * sizeof(char));
在我的 gcc 编译器中,当我使用 strlen(ch_pointer)
、2
或 4
作为答案时返回。
如果我使用的数字太大(例如 100)作为长度,它也会显示 strlen(ch_pointer) == 0
。
如果我在 visual studio 中将其编写为:
ch_pointer = (char *)malloc(((length + 1) * sizeof(char)) / 2 - 1);
这是唯一完美运行的情况。
get_number()
函数很好,它只是确保您将键入一个 int 类型。
void main() {
char *ch_pointer = '\0';
int length = 0;
printf("Please write down your sentence length in characters (including spaces): ");
length = get_number();
ch_pointer = (char *)malloc(((length + 1) * sizeof(char)) / 2 - 1);
ch_pointer[strlen(ch_pointer) - 1] = '\0';
printf("Please write down your sentence: ");
for (int filling = 0; filling < strlen(ch_pointer); filling++)
scanf(" %c", &ch_pointer[filling]);
for (int printing = 0; printing < strlen(ch_pointer); printing++)
printf("%c", ch_pointer[printing]);
free(ch_pointer);
}
如果我写下 4
甚至 100
以获得数组长度 5
或 101,两个编译器的工作方式相同
以 '\0'
结尾 & 让我完美地输入和打印:
length = 4
strlen(ch_pointer) == 4
或
length = 100
strlen(ch_pointer) == 100