0

inverting a string of bits in C but when I return it back to the main function it comes out as random characters.. what should I do?

const char * invert1(char S_string[]) {
    char new_S[strlen(S_string)]; //malloc(strlen(S_string)*sizeof(int));
    char *ptr = new_S;

    printf("S_string = %s\n", S_string);
    int i = 0;

    for(i = 0; i < strlen(S_string); i++) {
        
        if(S_string[i] == 48){
            new_S[i] = 49;
        }
        else if(S_string[i] == 49){
            new_S[i] = 48;
        }
        else{
            return "354";
        }
        printf("1new_S = %s\n", new_S);
        printf("i = %d\n", i);
    }
    printf("%s\n", new_S);
    printf("%s", ptr);
    
    printf("%s", "yeup");
    return ptr;
}

int main(int n, int k){
    char S[] = "1";
    //char temp[strlen(S)] = invert1(S);

    printf("%s", invert1(S));
}

This is the output:

S_string = 1
1new_S = 0
i = 0
0
0yeup v~v�S��@

After "yeup", it should print "0" What am I doing wrong?

  • 3
    Why did you remove the `malloc`? Now you are returning a reference to a local variable which becomes invalid when the function exits. Using such a variable outside the function results in Undefined Behaviour. – kaylum Sep 30 '21 at 00:01
  • 2
    Another issue is that you are not ensuring `new_S` is NUL terminated. – kaylum Sep 30 '21 at 00:02
  • 1
    Does this answer your question? [How to access a local variable from a different function using pointers?](https://stackoverflow.com/questions/4570366/how-to-access-a-local-variable-from-a-different-function-using-pointers) – kaylum Sep 30 '21 at 00:09
  • @kaylum I tried malloc but it would give me an error for new_S[i] = 48; (error: subscripted value is neither array nor pointer nor vector). and how do I make it NULL-terminated? Also, is there way to not use struct and still return the string safely? – WeeWooWeeWoo Sep 30 '21 at 00:09
  • The obvious response is that you did it wrong. But can't tell you what exactly without seeing the exact code. My guess is that you declared the wrong variable type. Should be `char *new_S = malloc(strlen(S_string)+1);` and to NUL terminate do `new_S[strlen(S_string)] = '\0';` – kaylum Sep 30 '21 at 00:12
  • Note: reversing a string of `1`s and `0`s is not different from reversing a string of characters. – wildplasser Sep 30 '21 at 00:17
  • I posted the whole code, you can try running it (i included stdio, stdlib and string .h). as for the nul-terminated, I get error (error: variable-sized object may not be initialized) – WeeWooWeeWoo Sep 30 '21 at 00:19
  • if it helps, this is what I am working on (https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/) – WeeWooWeeWoo Sep 30 '21 at 00:21
  • 1
    Already told you what the problem with the current code is. Now you have moved on to code we can't see. Post a new question. – kaylum Sep 30 '21 at 00:22

0 Answers0