【发布时间】:2021-06-06 18:18:56
【问题描述】:
我编写了这个程序,它询问用户一个名字,然后打印这个名字。详细步骤如下:
- 询问用户名称(即句子)的字符数。它包含空格和终止符
\0,然后存储它; - 它使用
num_char地址创建一个内存块,并将第一项的地址存储在ptr中; - 在
else部分中,声明了一个未知大小的数组,用于存储名称,并将其首地址分配给ptr; - 然后为数组分配大小
num_char;
代码如下:
#include <stdio.h>
#include <stdlib.h>
//an attempt at a program that asks for a name, stores it in an array and then prints it
int main() {
int num_char;
char *ptr;
printf("input number of characters of your name (spaces and terminator character included): ");
scanf("%d", &num_char);
ptr = char *malloc(num_char * sizeof(char)); //creates a block of mem to store the input name, with the same size, and then returns the adress of the beginning of the block to ptr
if (ptr == NULL) {
printf("allocation not possible");
} else {
ptr = char name[]; //ptr stores the adress of the first char in string
char name[num_char], //declaration of an array with num_char elements
printf("input name: ");
scanf("%s", name);
printf("input name was: %s", name);
}
return 0;
}
但是我得到三个编译错误:
- “'char' 之前的预期表达式”
ptr = char *malloc(num_char * sizeof(char) );和ptr = char name[]; - “预期的声明说明符或字符串常量之前的'...'”
printf("input name: ");
我是一名刚开始学习 C 和一般编程的大学生,因此非常感谢详细解释任何类型的错误以及如何修复它:)
【问题讨论】:
-
ptr = char *malloc(num_char * sizeof(char) )只需删除char *。如果您要进行强制转换,那么它需要是(char *),但在 C 中不需要强制转换。 -
char name[num_char],->char name[num_char]; -
ptr = char *malloc(num_char * sizeof(char));应该是ptr = malloc(num_char);你 shouldn't cast the result of malloc,而sizeof(char)根据定义是 1,所以乘以sizeof(char)是没有意义的。 -
@chqrlie
ptr = char name[]; -
这是一个奇怪的赋值,所以你为
ptr分配内存,然后你必须为ptr分配一个数组?这就是内存泄漏。
标签: arrays c pointers compiler-errors malloc