c - Access to specific elements of array -
c - Access to specific elements of array -
im trying create c programme create little wordlist .txt file. created char array of 10 elements, , need every possible 4 letter combination of 10 chars.
so, figured have 4 loops within each other take elements array , create 4 letter combinations , write .txt.
my problem using pointers access elements of array. doing:
char array[10] = {'a', 's' ,'d', 'f', 'g', 'h', 'j', 'k', 'l', 'm'}; char input[4]; char *p; p=array; file *pfile = null; char *filename = "output.txt"; pfile = fopen(filename, "w"); for(i=0;i=3;i++) { for(j=0;j=3;j++) { for(k=0;k=3;k++) { for(l=0;l=3;l++) { strcpy(input, *(p+i)); strcat(input, *(p+j));//"gluing" first , sec element of new string strcat(input, *(p+k));//same line before strcat(input, *(p+l)); strcat(input, "\n"); fprintf(pfile, input); //end of loops, closing .txt file etc.
this compiles nicely , terminal starts, crashes. think because of error in accessing array elements.
any ideas? much appreciated!
additional info> when create:
char string[10] = "assd"; //and insert instead of *(p+i) anywhere works supposed
strcpy
, strcat
both go on until find null, , array doesn't have one. each slot in array single character, followed next single character, etc. strcpy begin copying selected letter till beyond end of entire list. finally, you're adding 5th element ("\n") 4 element array. instead, this:
input[0] = *(p+i); input[1] = *(p+j); input[2] = *(p+k); input[3] = *(p+l); input[4] = "\n";
this should work. note, however, fprintf might easier way go:
fprintf(pfile, "%c%c%c%c\n", *(p+i), *(p+j), *(p+k), *(p+l));
i'm tempted go on playing "code golf" code, because there number of things improve in long run, think i'll stop @ getting working (though find amazing compiler accepts first line without listing letters using quotes 'a'
). 1 final comment though: don't need p
variable @ all. can array[i]
in above *(p+i])
.
c arrays pointers
Comments
Post a Comment