Pregunta

I was trying to write a program to convert numbers into Roman Numerals. (It is a duplicate of the code found here: How to convert integer value to Roman numeral string? ) I am pretty sure the program logic is al-right. Here is my code:

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

int main(){
const char *huns[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
const char *tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
const char *ones[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
const int size[] = {0, 1, 2, 3, 2, 1, 2, 3, 4, 2};

char *_buffer;
unsigned int num;

input:
printf("Enter number to convert:\n");
scanf("%ud", &num);

if(num>4000)
    goto input;

while(num>=1000){
    *_buffer++ = 'M';
    num -= 1000;
}

strcpy (_buffer, huns[num/100]); _buffer += size[num/100]; num = num % 100;
strcpy (_buffer, tens[num/10]);  _buffer += size[num/10];  num = num % 10;
strcpy (_buffer, ones[num]);     _buffer += size[num];

*_buffer ='\0';
printf("%s", _buffer); // This is where the Runtime Error occurs.

return 0;
}

Can someone please explain why printf() causes a runtime error here? I tried puts() as well and it didn't work. I've tried compiling and running in Code:Blocks 13.11 (MINGW gcc) as well as http://ideone.com , but both give the same error.

¿Fue útil?

Solución

you problem is (and the compiler has probably already issued a warning about this) _buffer is uninitialized, meaning that it is pointing to some random address in memory - hence your runtime error. Change your code to

char buffer [128];
char *_buffer=buffer;

and printf buffer (not _buffer).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top