C - 为 char 类型数组分配内存

C - Allocating memory for char type array

我的任务是创建 char 类型数组,然后输入该数组应包含的元素数,然后为该数组分配内存并在将所有元素输入数组后打印它。问题是,如果数组是 int 类型,我知道该怎么做,但对于 char,我只打印随机字符。我写了这段代码:

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

int main() {


    int n, i;
    char *arrA;


    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter array elements: \n");
    arrA = (char*)malloc(n * sizeof(char));
    for (i = 0; i < n; ++i) {
        scanf("Array element: %c \n", arrA + i);
    }

    for (i = 0; i < n; ++i) {
        printf("%d. array element is: %c\n", i + 1, arrA + i);
    }

    free(arrA);
    return 0;
}

如何让它适用于 char 类型数组?

换行:

printf("%d. array element is: %c\n", i + 1, arrA + i);

至:

printf("%d. array element is: %c\n", i + 1, *(arrA + i));

或:

printf("%d. array element is: %c\n", i + 1, arrA[i]);

因为现在您正在尝试打印指针本身而不是它的内容。

另请阅读 this link on why not to cast the result of malloc and this one 检查 malloc 的结果。

arrA + i 是一个 指针 。您需要在 printf 参数中使用 *(arrA + i),或者更清晰且完全等效的 arrA[i].

注意:sizeof(char) 在 C 标准中是 1,所以是多余的。也不要在右侧投射 malloc 。参见 Do I cast the result of malloc?。最后,始终检查 malloc 的结果。如果是 NULL 则内存分配失败。

其他答案的补充:

你想要这个:

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

int main() {
  int n, i;
  char *arrA;

  printf("Enter number of elements: ");
  scanf("%d", &n);
  printf("Enter array elements followed by [Enter] key: \n");

  getc(stdin);  // absorb \n (scanf oddity)

  arrA = malloc(n * sizeof(char));

  for (i = 0; i < n; ++i) {
    scanf("%c", &arrA[i]);
  }

  for (i = 0; i < n; ++i) {
    printf("%d. array element is: %c\n", i + 1, arrA[i]);
  }

  free(arrA);
  return 0;
}