Reputation: 5378
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
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
Reputation: 1114
As char * is a array of string, you should use indexer buf[index] with it...
Upvotes: 2
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
Reputation: 273179
You can address a string (char*) as an array of char:
char x = buf[0];
Upvotes: 1
Reputation: 4783
You can have indexing.
if (buf != NULL) {
int i = 0;
while (buf[i] != '\0') {
// Do Processing
++i;
}
}
Upvotes: 2