bogatyrjov
bogatyrjov

Reputation: 5378

Passing string to a function in C

The code given below reads file contents to buffer, and then does something with it.

char *getData(){
    char *buf = (char*) malloc(100);
    //write file contents to buf
    return buf;
}

char *bar(char *buf){
    //do something with buf
    return buf;
}

int main(void){
    char *result;

    result = bar(getData());

    return 0;
}

The return buf; at line 9 works fine - it returns the whole string. The question is how can I access individual characters in buf in function bar?

Upvotes: 3

Views: 783

Answers (6)

Matteo Italia
Matteo Italia

Reputation: 126777

If you want to access the individual characters, you can do it as you'd do with any string in any other place: buf[index] (for pointers ptr[index] is exactly the same as *(ptr+index)).

By the way, in that code there's a malloc but not its corresponding free - you're leaking memory. In such a small program the problem is not evident (the application is terminated immediately, so all the still non-deallocated memory is automatically reclaimed by the OS), but in larger programs the problem can become serious.

Upvotes: 7

Genius
Genius

Reputation: 1114

As char * is a array of string, you should use indexer buf[index] with it...

Upvotes: 2

Platinum Azure
Platinum Azure

Reputation: 46183

Maybe I'm not understanding your question, but at first glance I'd say you just need to use array accessing:

char *bar(char *buf)
{
  char newFifthCharacter = 'X';
  buf[4] = newFifthCharacter;
  return buf;
}

Note that you need to have a way to do bounds-checking so you don't write beyond the end of the array. You can either use the strlen function in bar, or you can have an integer parameter containing the length. Passing the length is probably better practice.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273179

You can address a string (char*) as an array of char:

 char x = buf[0];

Upvotes: 1

Vinay
Vinay

Reputation: 4783

You can have indexing.

if (buf != NULL) {
    int i = 0;
    while (buf[i] != '\0') {
        // Do Processing
        ++i;
    }
}

Upvotes: 2

Josh Matthews
Josh Matthews

Reputation: 13026

buf[i] (or *(buf + i)) is ith character in buf.

Upvotes: 1

Related Questions