c - Allocate memory to char pointer array as it is read in -
i need read white space separated words stdin, use emalloc function allocate memory each word read in.
i finding confusing, here have written far.
#include <stdio.h> #include <stdlib.h> int main (void) { #define size 100 char* username[100]; int i; int p; /* read words array */ for(i = 0; < 100; i++) { username[i] = calloc(size, sizeof(char)); scanf("%s",username[i]); } /* print out array */ (p = 0; p < 100; p++) { printf("%s", username[p]); } return 0; }
i not sure whether reading words in correctly using scanf , pretty sure memory allocation not quite correct. coming java, memory allocation tricky wrap mind around. how come not include & infront of username[i] in scanf function?
your code fine few problems:
you should free'ing memory array of pointers point to.
the use of scanf() dangerous buffer overflow occur.
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (void) { #define size 100 char* username[100]; char *nl; int i; int p; /* read words array */ for(i = 0; < 3; i++) { username[i] = calloc(size, sizeof(char)); printf("enter word %d:", i+1); fgets( username[i], size, stdin ); // remove newline if ((nl = strchr(username[i], '\n'))) { *nl = '\0'; } } /* print out array */ (p = 0; p < 3; p++) { printf("[%s]\n", username[p]); free( username[p] ); } return 0; }
output:
~/src/svn/misc > ./a.out enter word 1:one enter word 2:two enter word 3:three 1 2 3
Comments
Post a Comment