使用指针打印字符串:运行时错误

时间:2014-04-27 08:16:20

标签: arrays string pointers runtime-error printf

我正在尝试编写一个程序,将数字转换为罗马数字。 (它是这里找到的代码的副本:How to convert integer value to Roman numeral string?)我很确定程序逻辑是正确的。这是我的代码:

#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;
}

有人可以解释一下printf()导致运行时错误的原因吗?我也试过了puts()但它没有用。我尝试在代码:块13.11(MINGW gcc)以及http://ideone.com中编译和运行,但两者都给出了相同的错误。

1 个答案:

答案 0 :(得分:0)

你的问题是(并且编译器可能已经发出了关于此的警告)_buffer未初始化,这意味着它指向内存中的某个随机地址 - 因此您的运行时错误。 将您的代码更改为

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

和printf buffer(不是_buffer)。