2012-02-25 12 views
1

私は、指定された文字に達するまで最初のn文字を返す関数を持っています。文字列の次の単語にptrを渡したい。私はこれをどのように達成するのですか?ここに私の現在のコードです。Cプログラミングのローカル文字ポインタ

char* extract_word(char* ptrToNext, char* line, char parseChar) 
// gets a substring from line till a space is found 
// POST: word is returned as the first n characters read until parseChar occurs in line 
//  FCTVAL == a ptr to the next word in line 
{ 
    int i = 0; 
    while(line[i] != parseChar && line[i] != '\0' && line[i] != '\n') 
    { 
     i++; 
    } 

    printf("line + i + 1: %c\n", *(line + i + 1)); //testing and debugging 

    ptrToNext = (line + i + 1); // HELP ME WITH THIS! I know when the function returns 
            // ptrToNext will have a garbage value because local 
            // variables are declared on the stack 

    char* temp = malloc(i + 1); 

    for(int j = 0; j < i; j++) 
    { 
     temp[j] = line[j]; 
    } 
    temp[i+1] = '\0'; 

    char* word = strdup(temp); 
    return word; 
} 
+0

'word'はスタック上にありますが、' word'が指すデータはありません。 – Mahesh

答えて

3

あなたはをchar型へのポインタにするポインタである引数を渡すと思います。この関数では、ポインティングされたポインタの値を変更することができます。つまり

char * line = ...; 
char * next; 
char * word = extract_word(&next, line, 'q'); 

そして、あなたの関数内...

// Note that "*" -- we're dereferencing ptrToNext so 
// we set the value of the pointed-to pointer. 
*ptrToNext = (line + i + 1); 
0

では、あなたが(strspn支援するためのライブラリ関数があります)strcspn()この種の問題のために非常に便利になります。

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

char *getword(char *src, char parsechar) 
{ 

char *result; 
size_t len; 
char needle[3] = "\n\n" ; 

needle[1] = parsechar; 
len = strcspn(src, needle); 

result = malloc (1+len); 
if (! result) return NULL; 
memcpy(result, str, len); 
result[len] = 0; 
return result; 
} 
関連する問題