C - Array of words -
i'm new programming, sorry if question seems trivial. have looked answer, can't straight one. we've covered in class, brain failing me right .
in c, need make array each element corresponds word.
edit: remembered should pointer array. i'm doing...
main() { char *line[maxline]; // points beginning of words in compare[] char compare[maxline]; // words read in int counter[maxline]; // counter words appear more once char c; int = 0; int n; (n=0; c!=eof; n++){ while ((c=getchar())!=' '||c!='\n'||c!=eof){ compare[i]=c; i++; } line[n]=compare; = 0; }
i'm aware that's not whole thing because need make compare have new address, how 1 suggest going doing that? need use structs or there way? should using malloc that?
i apologize if asked stupid question. since first post here, input on way went asking question appreciated since respect community incredibly , not want ruin silly questions. oh, input on question appreciated :)
thanks, slashstar
something should work (linux) windows need remove \r @ end
char buf[maxline]; char** wordsz = malloc( maxnumberofwords * sizeof(char*) ); int wordcount = 0; while (fgets( buf, maxline, stdin )!=null && wordcount<maxnumberofwords) { int len = strlen(buf); if ( buf[len-1] == '\n' ) buf[len-1]='\0'; wordsz[wordcount] = malloc( strlen(buf) + 1 );// assuming sizeof(char)==1 + \0 strcpy(wordsz[wordcount++], buf); }
fgets returns null when press eof, cannot overwrite memory if enter long string scanf , allocating space need (part maxnumberofwords)
Comments
Post a Comment