0

Trying to solve a problem on projectlovelace.net. I can't figure out why I can't assign values through a pointer as if it were an array. I thought that was possible.

It's been a while since I coded in C, so I'm sure there's a bone-headed obvious reason. (The problem requires me to both return the string and change the string, in case you wondered.)

#include <stdio.h>
#include <string.h>

char* rna(char* dna) {
    size_t i, len = strlen(dna);
    char rna[len + 1];

    rna[len] = '\0';

    for(i = 0; i < len; i++){
        char letter = dna[len - 1 - i];
        if(letter == 'T')
            letter = 'U';
        rna[i] = letter;
    }

    // problem is here.
    for(i = 0; i < len; i++)
        dna[i] = rna[i];

    return dna;
}

int main(void){

    char *dna = "CCTAGGACCAGGTT";
    printf("Input DNA: %s\nOutput RNA: %s\n", dna, rna(dna));
    return 0;
}

Even using dna[0] = 'X' causes a segfault.

Korgan Rivera
  • 495
  • 3
  • 9
  • 1
    Modifying string literals is prohibited. – MikeCAT Apr 19 '21 at 18:16
  • 1
    `dna` is a pointer to a string literal, you can't modify those. – anastaciu Apr 19 '21 at 18:16
  • 1
    `char dna[] = "CCTAGGACCAGGTT";` is what you should use. – anastaciu Apr 19 '21 at 18:17
  • Yeah, figured that out right after I posted it. However, there's a second problem. The printf line seems to run rna(dna) before printing dna first. If I use two separate printf statements, it fixes it. But, is there a way to have them evaluate in the correct order? – Korgan Rivera Apr 19 '21 at 18:20
  • 1
    Make `rna` behave like `strcpy` by passing the distinct input and output arrays. Define the input and output arrays in the caller. Don't do it in the callee. – Jeff Holt Apr 19 '21 at 18:23
  • `dna` is being modified in the function. Aside from Jeff's solution which is what I would probably do, you can pass a copy of `dna` instead of the original to the function, or alternatively allocate memory in the function for `rna` and return that instead. – anastaciu Apr 19 '21 at 18:33

0 Answers0