Passing a string to a function in C

The code below reads the contents of the file into a 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;
}

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

+3
source share
6 answers

If you want to access individual characters, you can do it the same way as with any string anywhere else: buf[index](for pointers, ptr[index]exactly the same as *(ptr+index)).

, malloc, free - . ( , ), .

+7

.

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

char * - , indexer buf [index] ...

+2

buf [i] ( * (buf + i)) - buf.

+1

(char *) char:

 char x = buf[0];
+1

, , , :

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

Please note that you need to be able to perform border checks so that you do not write outside the array. You can use the function strlenin bar, or you can have an integer parameter containing the length. Passing the length is probably better.

+1
source

Source: https://habr.com/ru/post/1774136/


All Articles