c - Read strings from console -
this question has answer here:
i wanna write program array of pointers char store strings read console in it. string determined \n. ideas how can this?
code mix of pseudocode far:
char** arr; arr = malloc(sizeof(char*) * 5); arr = malloc(sizeof(char) * 10); while (no \n read) { // store string in array }
i have no clue how this.
#include <stdio.h> #include <stdlib.h> int main(){ int i; char **arr; arr = malloc(sizeof(char*) * 5);//for 5 string for(i=0;i<5;++i){ arr[i] = malloc(sizeof(char) * 10);//reserved storage space length 9 scanf("%9[^\n]%*c", arr[i]);//read until \n, , discard \n } printf("\n"); //check print , free for(i=0;i<5;++i){ puts(arr[i]); free(arr[i]); } free(arr); return 0; }
int i, n; char **arr; arr = malloc(sizeof(char*) * 5); for(i=0;i<5;++i){ arr[i] = malloc(sizeof(char) * 10); } i=0; while(i<5 && 1==scanf("%9[^\n]%*c", arr[i])) ++i; n = i; printf("\n"); //check print for(i=0;i<n;++i){ puts(arr[i]); } //deallocate for(i=0;i<5;++i) free(arr[i]); free(arr);
Comments
Post a Comment