简体   繁体   中英

Function is not returning anything in C

I am trying to return a string in a C program. The program is a roman numeral encoder and takes and integer and returns a string as roman numerals:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *solution(int n);
int main() {
  printf("%s", solution(2253));
  return 0;
}
char *solution(int n) {
  char res[] = "";
  char *resPtr = res;
  while(n != 0)
  {
    if (n >= 1000)
    {
      strncat(res, "M", 1);
      n -= 1000;
    }
    ...
  }
  return resPtr;
}

The pointer is not returning anything

Two issues:

  1. Your string is too short. It is actually only 1 byte long and only accommodate the null terminator.
  2. It is automatic storage variable and it stops to exist when function returns.
  3. strncat will not grow the string.

Example:

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

const char *hundreds[] = {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
const char *tens[] = {"X", "XX",    "XXX",  "XL",   "L",        "LX",   "LXX",  "LXXX",     "XC",   };
const char *digits[] =  {"I","II","III","IV","V","VI","VII","VIII","IX"};


char *solution(int n);

int main() 
{
    char *p;
    printf("%s", p = solution(2253));
    free(p);
    return 0;
}



char *solution(int n) 
{
    char *resPtr = malloc(n / 1000 + 4 + 4 + 4 + 1);
    size_t pos = 0;
    if(resPtr)
    {
        while(n >= 1000)
        {
            resPtr[pos++] = 'M'; // no need of expensive strncat function
            n -= 1000;
        }
        if(n / 100)
        {
            strcpy(&resPtr[pos], hundreds[n / 100 - 1]);
            pos += strlen(hundreds[n / 100 - 1]);
            n = n % 100;
        }
        if(n / 10)
        {
            strcpy(&resPtr[pos], tens[n / 10 - 1]);
            pos += strlen(tens[n / 10 - 1]);
        }
        n = n % 10;
        if(n) strcpy(&resPtr[pos], digits[n - 1]);
    }
    return resPtr;
}

https://godbolt.org/z/1sadrb

char res[] is local variable to the function and it goes out of scope after you exit your function.

use strcpy instead, use a bigger string (you can go for dynamic memory allocation)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM