-5

Why does this C code return the warning in the title?

char n_zeroes(int n) {
  char str[n];

  int i;
  for (i = 0; i < n; i++) {
    str[i] = '0';
  }

  return str;
}
Fela Maslen
  • 2,022
  • 3
  • 25
  • 46
  • Also see [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Lundin Feb 09 '16 at 13:45

2 Answers2

4

Your function is declared to return char and you are returning an array of char. But even if you fix the return value which should be char * it's still wrong because you should not return a local variable, instead pass the array as an argument to the function like this

void
n_zeroes(int n, char *str)
{
    for (int i = 0 ; i < n ; ++i)
        str[i] = '0';
}

but this is essentially the same as

memset(str, '0', n);

also, note that this array filled just with zeroes does not represent a string, to make it a valid string that you can use with str* functions or pass to *printf() functions with the "%s" specifier it needs one extra element at the end with the specific value of '\0' or 0.

As you can understand from the error your code is making a pointer, from an integer without an explicit cast. This is because you are allowed to do that, i.e. to cast an integer to a pointer. Whether that's a correct thing to do or not is entirely a different thing, but the standard allows many things that can be misused too. That's the great thing about , with great power comes greate responsibility.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

The answer to your question is, because str is a pointer to an array, the compiler casts it to the intended return value (char, which translates to a signed integer 8 bits usually 1 byte wide) and senses that there's something wrong between your code and your intentions...

The answer to your problem is, you can't do what you're intending here this way in C. To fill a char array with zeroes (a task better left to memset() instead of using a for loop) in a function and use it in the calling code, you need to pass a pointer to the reserved array to the function.

Murphy
  • 3,827
  • 4
  • 21
  • 35
  • Not necessarily `8` bits, `CHAR_BIT` bits. – Iharob Al Asimi Feb 09 '16 at 13:22
  • Well, as this is technically correct, I intend to postpone confusing the OP with details until later. For most platforms this approximation should do, and here it doesn't help to get the code right. – Murphy Feb 09 '16 at 13:28