Search code examples
cc-stringsstring-literalsfunction-definition

How can I return a string whose characters are being modified inside a function in C


I want to make a function that takes one int argument 0 or 1, and depending on it returns a string "a==b" or "a!=b".

To return a string, it should be a string literal, char *s but that doesn't support s[0] = 'a'. But if I make it a char s[20] then I can't return it.

This is what I have tried doing. But this does not work.

#include <stdio.h>

char *func(int param){
    char s[20];
    
    s[0] = 'a';
    
    if(param)
        s[1] = '!';
    else
        s[1] = '=';
    
    s[2] = '=';
    s[3] = 'b';
    
    return s;
}

int main()
{
    printf("String: %s", func(0));
    return 0;
}

How can I do the same?

(I also read that I can do the same by allocating memory in the heap and returning it, but then I will have to free it in the main function. So, I don't want to do this.)

Thank you in advance.


UPDATE

A possible solution to the above example is to return two different strings "a==b" or "a!=b" but this is not the approach I am looking forward to. This is just a simple example of what I want to do.

What I actually want to do is to traverse a input string of '0's and '1's and depending on that return another string of '0's and '1's (say complement of that string), so I would want to do s[i] = '0'. Then what should I do?


Solution

  • - You may allocate the memory with malloc and return a pointer to it. The caller will be available for freeing the memory.

    - You may pass a pointer to preallocated string:

    char *func(char *s, int param) {
        ...
        return s;
    }
    
    int main() {
       char s[20];
       printf("...", func(s, 20));
       // or
       printf("...", func((char[20]){0}, 20));
    }
    

    - You may use an array with static storage duration defined either at file scope or at block scope (or that could be a pointer with static storage duration to a valid array) - ie. use a global variable:

    char s[20];
    char *func(int param){
        ....
        return s;
    }
    // or
    char *func(int param){
        static char s[20];
        ....
        return s;
    }