Question

I already asked on question earlier about the string function strstr, and it just turned out that I had made a stupid mistake. Now again i'm getting unexpected results and can't understand why this is. The code i've written is just a simple test code so that I can understand it better, which takes a text file with a list of 11 words and i'm trying to find where the first word is found within the rest of the words. All i've done is move the text document words into a 2D array of strings, and picked a few out that I know should return a correct value but are instead returning NULL. The first use of strstr returns the correct value but the last 3, which I know include the word chant inside of them, return NULL. If again this is just a stupid mistake I have made I apologize, but any help here on understanding this string function would be great.

The text file goes is formatted like this:

chant  
enchant    
enchanted    
hello    
enchanter    
enchanting    
house    
enchantment    
enchantress    
truck    
enchants

And the Code i've written is:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {

FILE* file1;
char **array;
int i;
char string[12];
char *ptr;

array=(char **)malloc(11*sizeof(char*));

for (i=0;i<11;i++) {
    array[i]=(char *)malloc(12*sizeof(char));
}

file1=fopen(argv[1],"r");

for (i=0;i<11;i++) {
    fgets(string,12,file1);
    strcpy(array[i],string);
}

ptr=strstr(array[1],array[0]);
printf("\nThe two strings chant and %s yield %s",array[1],ptr);
ptr=strstr(array[2],array[0]);
printf("\nThe two strings chant and %s yield %s",array[2],ptr);
ptr=strstr(array[4],array[0]);
printf("\nThe two strings chant and %s yield %s",array[4],ptr);
ptr=strstr(array[5],array[0]);
printf("\nThe two strings chant and %s yields %s",array[5],ptr);


return 0;
}

No correct solution

OTHER TIPS

Get rid of the trailing \n after fgets().

for (i=0;i<11;i++) {
    fgets(string, sizeof string, file1);
    size_t len = strlen(string);
    if (len > 0 && string[len-1] == '\n') string[--len] = '\0';
    strcpy(array[i], string);
}
char *chomp(char *str){
    char *p = strchr(str, '\n');
    if(p)
        *p = '\0';
    return str;
}
...
strcpy(array[i], chomp(string));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top