I'm writing a code that reads in a list of characters (using redirection), but the string I'm storing the characters to has a size of 41. The number of characters do not come close to the size of the array, therefore I need to use malloc() in order to get the exact array size. When I print the array without using the malloc function is prints symbols and other gibberish along with the string. I need to malloc the string so the symbols and gibberish won't be included.
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char c;
char r1[41];
int a = 0;
while(scanf("%c", &c) != EOF) {
if(c >= 'A' && c <= 'Z' || c == '[' || c == '.' || c == '!') {
r1[a] = c;
a++;
}
}
printf("\nThe string is: %s\n", r1);
return 0;
}
Output:
The string is TR[!.DFQ▒ ▒ ▒ 這
stringis an array of 42 pointers tochar. You wantchar string[40+1];. (And of course you'll need to store some value in it.)stringarray are uninitialized, which leads to further undefined behavior...