Home > Blockchain >  Problem with returning an array to a function in C
Problem with returning an array to a function in C

Time:04-26

My problem is that I can't return the processed string to the function. The function's job is that it must accept a string, change its letters, and return the processed string to the function.


char *dna_strand(const char *dna)
{
    int a;
   for (a = 1; *(dna a) != '\0' ; a  ) {
}
 char array[a];
    for (int i = 0; i < a;   i) {
        if ('A' == *(dna   i)) {
            array[i] = 'T';
        } else if ('T' == *(dna   i)){ 
            array[i] = 'A';
        } else{
            array[i] = *(dna   i);
        }
    }
      return array;
}

Error : [1]: https://i.stack.imgur.com/uwvCh.png

CodePudding user response:

The local variable char array[a]; is out of scope for caller so you cannot use that to return a value. Instead allocate memory on the heap with malloc() or as herestrdup():

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

char *dna_strand(const char *dna) {
    char *array = strdup(dna);
    if (!array) return array;
    for (int i = 0; array[i]; i  ) {
        if (dna[i] == 'A') array[i] = 'T';
        else if (dna[i] == 'T') array[i] = 'A';
    }
    return array;
}

int main() {
    char *s = dna_strand("ATTCG");
    printf("%s\n", s);
    free(s);
    return 0;
}

If you want to be fancy use strpbrk() to find the next letter we need to map instead of stepping one letter at a time:

char *dna_strand(const char *dna) {
    char *array = strdup(dna);
    for (char *p = array; p; p = strpbrk(p, "AT")) {
        if (*p == 'A') *p   = 'T';
        else *p   = 'A';
    }
    return array;
}

CodePudding user response:

You may not return a pointer to a local array with automatic storage duration because after exiting the function the array will not be alive and the returned pointer will be invalid.

You need to allocate an array dynamically.

Pay attention to that this loop

for (a = 1; *(dna a) != '\0' ; a  ) {

can invoke undefined behavior when the user will pass to the function an empty string.

You should write at least like

int a = 0;
while ( *(dna a) != '\0' )   a;
  a;

or

int a = 0;
do ; while ( *( dna   a   ) != '\0' );

After that you can allocate dynamically a character array

char *array = malloc( a );

CodePudding user response:

You cannot return a pointer to a local variable's address, because it will be destroyed when it will goes out from the function's scope.

Since, a is not a constant value, you cannot initialize array as static. Hence, the only option is left is using heap-allocation.

a can be initialize like this:

char *array = calloc(a   1, sizeof(char));

Note: calloc() is defined in stdlib.h header file.

  • Related