Home > Software engineering >  How to return variable?
How to return variable?

Time:10-11

I am writing a program that translates letters into morse code and then transmits them to an LED and blinks. I am not able to return the value ".- -..."

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

char *encode()
{
  char *name = "AB";
  char name_m[100] = "";

  for (int i = 0; i < strlen(name); i  )
  {
    if (name[i] == 65)
    {
      strcat(name_m, ".- ");
    }
    else if (name[i] == 66)
    {
      strcat(name_m, "-...");
    }
  };
  printf("%s", name_m);
  
  return name_m;
}

int main()
{
    char *name_m;
    name_m = encode();
    printf("\n%s", name_m);
}
main.c:22:10: warning: function returns address of local variable [-Wreturn-local-addr]
   22 |   return name_m;
      |          ^~~~~~
.- -...
(null)

CodePudding user response:

In C you cant return reference (pointer) to local variable as it stops to exist when function returns.

You need to pass te buffer to the function:

char *encode(char *name_m, const char *name)
{
  for (int i = 0; i < strlen(name); i  )
  {
    if (name[i] == 'A')
    {
      strcat(name_m, ".- ");
    }
    else if (name[i] == 'B')
    {
      strcat(name_m, "-...");
    }
  }
  printf("%s", name_m);
  
  return name_m;
}

allocate it dynamically:

char *encode( const char *name)
{
  char *name_m = malloc(100);

  if(name_m)
  {
    for (int i = 0; i < strlen(name); i  )
    {
        if (name[i] == 'A')
        {
        strcat(name_m, ".- ");
        }
        else if (name[i] == 'B')
        {
        strcat(name_m, "-...");
        }
    }
    printf("%s", name_m);
  }
  
  return name_m;
}

or the worst solution - define it as static

char *encode( const char *name)
{
  static char name_m[100];

  if(name_m)
  {
    for (int i = 0; i < strlen(name); i  )
    {
        if (name[i] == 'A')
        {
        strcat(name_m, ".- ");
        }
        else if (name[i] == 'B')
        {
        strcat(name_m, "-...");
        }
    }
    printf("%s", name_m);
  }
  
  return name_m;
}

CodePudding user response:

A simple solution to the problem, by reassigning the value to char*

name = name_m;
return name;
  • Related