アプリ版:「スタンプのみでお礼する」機能のリリースについて

strtol関数をmalloc()関数を使用して次のソースプログラムを修正しなさいを言われました。
どなたか詳しい方よろしくお願いします。

#include <limits.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>

int _space_sign(const char *s, const char **endptr);
int _space_sign(const char *s, const char **endptr)
{
int sign ;
while (isspace((unsigned char)*s))
++s;
sign = 0;
switch (*s)
{
case '-':
sign = -1;
// fall through
case '+':
++s;
break;
}
*endptr = s;
return sign;
}

long int strtolong(const char * s, char ** endptr, int base)
{
int c;
int sign = _space_sign(s, (const char**)&s);
long result;

if (s[0] == '0')
{
++s;
if ((s[1] | 0x20) == 'x')
{
if (base == 0 || base == 16)
{
++s;
base = 16;
}
}
else if (base == 0)
base = 8;
}
else if (base == 0)
base = 10;

result = 0;
for (; c = tolower((unsigned char)*s), isdigit(c) || ('a' <= c && c <= 'v'); s++)
{
int d ;
if( isdigit(c) )
d= c - '0' ;
else d = c - 'a' + 10;
if (d >= base)
break;
if (result > (LONG_MAX - d - sign) / base)
{
errno = ERANGE;
result = sign ? LONG_MIN : LONG_MAX;
}
else
{
result = result * base + d;
}
}

if (endptr != NULL)
*endptr = (char*)s;

if (sign != 0)
result = -result;
return result;
}
int main(void)
{
char s[128], *e;
long n;
int base;

printf("何進数で変換しますか。");
scanf("%d", &base);
printf("変換する数値を入力してください。");
scanf("%s", s);

n = strtolong(s, &e, base);

if (errno != ERANGE) {
printf("変換数値=%ld\n", n);
if (*e != '\0') {
printf("変換不可能部分=%s\n", e);
printf("%d文字目の\'%c\'が変換不可\n", e-s+1, *e);
}
}
else if (n == LONG_MAX)
printf("long値で表現できる値を上回りました。\n");
else if (n == LONG_MIN)
printf("long値で表現できる値を下回りました。\n");

return 0;
}

A 回答 (3件)

「strtol関数とmalloc()関数を使用して次のソースプログラムを修正しなさい」


ということなのかな?
    • good
    • 0

何のためにmallocを利用するのか理解に苦しむ。


ASCI相当のstrtolならmallocは必要としない。
なぜmallocを使用する必要があるのか理解しているのだろうか?
    • good
    • 0

日本語がおかしいので何をしていいのかわからんが, とりあえず strtolong がバグってるっぽいことはわかった.


EBCDIC って知ってる?
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!