-1

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)
auem
  • 45
  • 7
  • 2
    The name_m you return in encode() is a local variable, as the warning indicates. So you cant expect that value to be anything useful after encode() has returned. – J_Catsong Oct 10 '22 at 23:20
  • A couple solutions you could consider: pass in an statically allocated array from main or dynamically allocate some memory inside your encode function then return that memory. – SafelyFast Oct 10 '22 at 23:39
  • 1
    Does this answer your question? [Returning an array using C](https://stackoverflow.com/questions/11656532/returning-an-array-using-c) – user16217248 Oct 11 '22 at 00:09
  • Question has been answered here https://stackoverflow.com/questions/11656532/returning-an-array-using-c – John Demetriou Oct 11 '22 at 09:42

1 Answers1

2

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;
}
0___________
  • 60,014
  • 4
  • 34
  • 74