Reputation: 29
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?
Upvotes: 0
Views: 668
Reputation: 50882
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;
}
Upvotes: 1
Reputation: 5009
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.
Upvotes: 3
Reputation: 234865
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.
Upvotes: 2