C = Malloc copy elements of array put it to another array

So i Have an array with words and i want to search and find to that array for example words that have 5 letters, so I can copy them and put them to another dynamic array for further usage
[code]
int main()
{
/**/
char **wordarr, **wordpc;
int option=1, library, howmany, i,number, numwords=0,count=0;


//open the file
FILE *fp;
fp = fopen("file.txt", "r");
if (fp == NULL) {
fprintf(stderr, "File not found\n");
exit(1);
}
//counts the words in the file
int ch, letterCount = 0;
while((ch = fgetc(fp)) != EOF){
if(ch == ' ' || ch == '\n'){
count++;
}
else if(ch == ',' || ch == '.' || ch == '!' || ch == '?');
else
letterCount +=1;
}
printf("letterCount %d\ncount %d\n", letterCount, count);

//making the array
wordarr = (char**)malloc(sizeof(char*) * count);
for(i = 0; i<count; i++){
wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
}
//
//putting the words into the array

char buffer[10000];
fp = fopen("file.txt", "r");
char *tok;
i=0;
while( fgets(buffer, 10000, fp) != NULL){
tok = strtok(buffer, " .,!");

while (tok != NULL) {
strcpy(wordarr[(i)++], tok);
tok = strtok(NULL, " .,!");
}
}
fclose(fp);

/*int j=0;
for (j=0; j<i; j++) {
printf("[%s]\n", wordarr[j]);
}*/
////////////////

printf("\nWrite how many letters does the word have?\n");
scanf("%d", &number);
int len,*temp= NULL, *tempi= NULL;
//goes to the first array and searches for words with NUM characters
//stores the words to an array
for(i=0; i<count; i++){

len = strlen(wordarr[i]);
printf("%d", len);
if(strlen(wordarr[i]) == number){
//printf("%lu\n", strlen(wordarr[i]));
numwords++;
temp = (int*) realloc(tempi, numwords *sizeof(int));
if(temp != NULL){
tempi=temp;
tempi[numwords-1]= i;
}
}
}
//
wordpc = (char**)malloc(sizeof(char*) * numwords);
for(i = 0; i<numwords; i++){
wordpc[i] = (char*)malloc(sizeof(char) * WIDTH);
}
//
/*for(i=0; i<howmany; i++){
if(strlen(wordarr[i]) == number){
wordarr[tempi] = wordpc[i];
}
}*/




//Deallocate the memory
for (i=0; i<count; i++) {
free(wordarr[i]);
free(wordpc[i]);
}
//free(wordarr);
//free(wordpc);
return 0;
}[code\]
pointer_dest[5] = 0; //this variable can be a pointer or just an array.
memcpy(pointer_dest, pointer_source, 5);

you now has a valid 5 char c-string copied out of the original.



Last edited on
Topic archived. No new replies allowed.