2015-09-28 64 views
0

我想在另一個字符數組中找到一個字符串。我試圖比較它字符由charcter。但我無法訪問個人角色,我需要一些幫助。字符串的位置 - 從指針數組訪問單個字符串

代碼

#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; 
} 

謝謝您的幫助。我從上週開始用C語言學習編程。

+2

'而(計數<= LEN){'應該是'while(count amdixon

回答

1

修復

  • 在計數迭代< LEN(不< = LEN)
  • 使用strcmp簡化字符串比較(那是什麼它那裏)
  • 增量計數器count正確循環串列陣

代碼

#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; 
} 

輸出

$ 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) 

以上是與Valgrind的停止泄漏一個樣品運行..

+0

謝謝。我以錯誤的方式訪問了字符串。並感謝關於valgrind的提示。我接受你的答案。 – Mitty