0

I want to find a string inside another character array. I tried to compare it character by charcter. But I cannot access individual character, I need some help here.

code

#include <stdio.h>
#include "source.h"

int main()
{  
    char *str[] = {"one","two","three","four"};
    int index;    

    index= locate_string(str, 4, "one");
    printf("String one is in the position %d\n", index);

    return 0;
}

int locate_string(char **stringArray, int len, char * string)
{
    int count = 0;
    while(count <= len){
      int j = 0;
      char *temp = (*stringArray)[count];

      while(j < len){
        if(temp == string[j]){
            j++;                
        }
      }
      if(j == len-1){
        return count-j;
      }
    }
    return -1;
}

Thanks, for the help. I'm learning programming in C from last week.

1
  • 2
    while(count <= len){ should be while(count < len){. should use strcmp to compare strings Commented Sep 28, 2015 at 10:17

1 Answer 1

1

fixes

  • iterate over count < len ( not <= len )
  • use strcmp to simplify string comparison ( thats what its there for )
  • increment counter count to correctly loop over string array

code

#include <stdio.h>

int main(void)
{  
  char *str[] = {"one","two","three","four"};
  int index;    

  index = locate_string(str, 4, "one");
  printf("String one is in the position %d\n", index);

  return 0;
}

int locate_string(char **stringArray, int len, char *string)
{
  int count = 0;
  while(count < len)
  {
    if(!strcmp(stringArray[count], string))
    {
      return count;
    }
    ++count;
  }
  return -1;
}

output

$ gcc -g test.c -o test
$ valgrind ./test
==12705== Memcheck, a memory error detector
==12705== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12705== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==12705== Command: ./test
==12705== 
String one is in the position 0
==12705== 
==12705== HEAP SUMMARY:
==12705==     in use at exit: 0 bytes in 0 blocks
==12705==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==12705== 
==12705== All heap blocks were freed -- no leaks are possible
==12705== 
==12705== For counts of detected and suppressed errors, rerun with: -v
==12705== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

above is a sample run with valgrind to stop the leaks..

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I accessed the strings in a wrong way. And thanks for the tips about valgrind. I'm accepting your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.