简体   繁体   中英

C - Allocating memory for char type array

I have task to create char type array, and then enter number of elements that array should have, and after that allocate memory for that array and print it after entering all the elements into the array. Problem is, I know how to do it if array was int type, but for char I only for print of random charachters. I wrote this code:

#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;
}

How can I make it work for char type array?

Change line :

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

to :

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

or :

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

as right now you are trying to print the pointer itself and not its content.

Also read this link on why not to cast the result of malloc and this one on checking malloc 's result.

arrA + i is a pointer . You need to use *(arrA + i) in the printf argument, or the clearer and exactly equivalent arrA[i] .

Notes: sizeof(char) is 1 by the C standard, so is superfluous. Also don't cast malloc on the right hand side. See Do I cast the result of malloc? . Lastly, always check the result of malloc . If it's NULL then the memory allocation failed.

Complement to the other answers:

You want this:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM