Hello. There were difficulties in solving. The elements of an "unlimited" array are introduced. It is planned to output all elements ( char / int ) of the array, but displays other characters similar to alt codes. In the table Ascii I did not find ♫. How do I solve this problem?

 #include <stdio.h> #include <stdlib.h> #include <mem.h> int main() { int i; char* string = (char*) malloc(sizeof(char)); char c; printf("Enter your number:\n"); for (i = 0; (c = getchar()) == '\n'; i++) { if (string == NULL) { string = (char*) malloc(i + 2); } else { string = (char*) realloc(string, i + 2); } string[i] = c; string[i + 1] = '\0'; } for (i = 0; i < strlen(string); i++) { printf("a[%c]\n", string[i]); } free(string); system("pause"); return 0; } //a[` == 96] //a[♫ == 14] //a[u == 117] 
  • one
    It has already been discussed more than once, but still: getchar() returns an int . No need to store the result in char . - Ternvein

1 answer 1

Replace

 (c = getchar()) == '\n' 

on

 (c = getchar()) != '\n' 

Why - to explain?

And yet - for the educational task, relloc for each relloc will come down, but in general it is much more reasonable if necessary, if necessary, the memory size, say, doubles, tracking how much is already occupied.

  • please explain interestingly. - user197351
  • Because you had a cycle - "as long as you press Enter, perform actions", while you need to stop executing the cycle upon reaching the newline character ... - Harry