Linear Search in C

tsj

tsj

Permabanned
Joined
7 May 2004
Posts
1,051
Location
United Kingdom
I'm having some problems with a linear search in C
The values of the strings in arrdetails.team array are:

MAX_TEAMS is equal to 12

arrdetails[0].team = manu
arrdetails[1].team = liverpool
arrdetails[2].team = 0
arrdetails[3].team = 0
arrdetails[4].team = 0
arrdetails[5].team = 0
arrdetails[6].team = 0
arrdetails[7].team = 0
arrdetails[8].team = 0
arrdetails[9].team = 0
arrdetails[10].team = 0
arrdetails[11].team = 0

I am looking for the FIRST position of 0, in the case above it should be 2.

Code:
int linear_search() {

printf("\n **LINEAR SEARCH** \n");
        //find next team pos
        int i;
        char target[1];
        target[1] = "0";
        int tm_comp;

        for (i = 0; i < MAX_TEAMS; i++) {
printf("\nfound pos is called %s",arrdetails[i].team);
                tm_comp = (strcmp(arrdetails[i].team, target));
              if (tm_comp == 0) {
printf("\nfound pos is %d \n",i);
                return i;
                }
        }
        printf("\nfound pos is %d \n",i);
}

Please help me get this working

Thanks
 
Just had a play and the problem is due to the "target" variable/string,

If you replace:

char target[1];
target[1] = "0";

Those two lines with the following:

char *target = "0";



It should work properly, can't remember if that will allocate the memory properly as it's been too long since I last coded properly, but it should do and seems to work fine on my pc... :p
 
SKILL said:
Just had a play and the problem is due to the "target" variable/string,

If you replace:

char target[1];
target[1] = "0";

Those two lines with the following:

char *target = "0";



It should work properly, can't remember if that will allocate the memory properly as it's been too long since I last coded properly, but it should do and seems to work fine on my pc... :p


Sorry for late reply... I just tried that and it worked a treat. Thanks for that :D

Just gotta get this finished by next week now.
 
No worries, one thing though, always look at the compiler warnings, your code immediately gave a warning ('pointer to integer without a cast' iirc), which let me know what line it was and also an idea of what the problem was

Although the idea part only comes after seeing that warning hundreds of times :p
 
SKILL said:
No worries, one thing though, always look at the compiler warnings, your code immediately gave a warning ('pointer to integer without a cast' iirc), which let me know what line it was and also an idea of what the problem was

Although the idea part only comes after seeing that warning hundreds of times :p

nice one. thanks for advice m8
 
Back
Top Bottom