Search code examples
cfunction-pointersc-stringsstrlenfunction-declaration

C Code: Pass string from one function to another function


The main problem is: as soon as I send a string from one function to another, this second function doesn't really get the string as a parameter.

In detailled: I have a function void myfunc() contains a word. This word should be send to another function, so it can count the length of it. That's what I've written so far:

void myfunc(int (*countlength)(char ch)){

    char word[10] = "Hello\n";

    int result = countlength(&word);

    printf("Length of word: %d\n", result);
}

The word is being send to this function countlength(char* word):

int countlength(char* word) {
    int length = strlen(word);
    return length;
}

However the function countlength() can't count it's length and I don't know why...

The thing is, it works when the word is in the main function. Does anybody know why my Code doesn't work?


Solution

  • Two mistakes:

    void myfunc(int (*countlength)(char ch)){
    

    should be

    void myfunc(int (*countlength)(char* ch)){
    

    instead, as the function accepts char pointers.

    Secondly,

    int result = countlength(&word);
    

    should be

    int result = countlength(word);
    

    as word is already a char*.