创建使用数字作为大小整数字符数组 [英] Create char array of integer using digits as size

查看:159
本文介绍了创建使用数字作为大小整数字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建在C字符数组,用int的数字来填补它,但INT可以是任意数量的数字的。

I am trying to create a char array in C, to fill it with the digits of an int, but the int can be of any number of digits.

我使用的是被称为创建函数 getDigits(INT NUM),即返回位数整型了。

I'm using a created function called getDigits(int num), that returns a number of digits the int has.

char buffer[getDigits(number)] = "";
snprintf(buffer, sizeof(buffer),"%d",number);

但是当我编译使用gcc,它返回:

but when I compile using gcc, it returns:

错误:可变大小的物体可能无法初始化

我用尽了一切。当我把它声明为字符fileSizeStr [5] =; ,它的工作原理。我可以看到,当我尝试动态申报的缓冲区大小问题是上升的,但我真的想知道,如果是实现这一目标的一种方式。

I've tried everything. When I declare it as char fileSizeStr[5] = "";, it works. I can see the problem is rising when I try to declare the buffer size dynamically, but I would really like to know if is a way of achieving this.

推荐答案

扎克给在评论一个明智的解决办法:删除初始化。你会发现在这个答案工作实例,其中一些国家允许一个初始化,而其他的则没有。你会发现有关在注释的详细信息。下面的例子是从最明智的(恕我直言)下令至少明智的(使用涉及的malloc )。

Zack gave a sensible solution in the comments: Remove the initialisation. You'll find working examples in this answer, some of which do permit an initialisation, and others which don't. You'll find more information about that in comments. The following examples are ordered from most sensible (IMHO) to least sensible (which involve using malloc).

我建议您使用同样的伎俩,以确定有多少字节需要存储一个 INT 值十进制数字,你会使用八进制:除以总数在 INT 位3,并添加任何迹象和NUL终止。 DIGIT_COUNT 可以写成一个preprocessor宏像这样:

I suggest using the same trick to determine how many bytes are necessary to store an int value as decimal digits as you'd use for octal: Divide the total number of bits in an int by 3 and add for any sign and NUL termination. digit_count could be written as a preprocessor macro like so:

#include <limits.h>
#include <stddef.h>
#include <stdio.h>

#define digit_count(num) (1                                /* sign            */ \
                        + sizeof (num) * CHAR_BIT / 3      /* digits          */ \
                        + (sizeof (num) * CHAR_BIT % 3 > 0)/* remaining digit */ \
                        + 1)                               /* NUL terminator  */

int main(void) {
    short short_number = -32767;
    int int_number = 32767;
    char short_buffer[digit_count(short_number)] = { 0 }; /* initialisation permitted here */
    char int_buffer[digit_count(int_number)];
    sprintf(short_buffer, "%d", short_number);
    sprintf(int_buffer, "%d", int_number);
}

正如你所看到的,在这里,人们强大的好处是, DIGIT_COUNT 可用于无需修改任何整数类型:字符 INT 长长,以及相应的无符号类型。

As you can see, one powerful benefit here is that digit_count can be used for any type of integer without modification: char, short, int, long, long long, and the corresponding unsigned types.

通过比较一个小缺点是,你浪费存储几个字节,特别是对于像 1 小的值。在许多情况下,这种解决方案的简单性多于弥补了这一点;需要code算在运行时,十进制数字将占用比这里浪费的内存空间。

One minor downside by comparison is that you waste a few bytes of storage, particularly for small values like 1. In many cases, the simplicity of this solution more than makes up for this; The code required to count the decimal digits at runtime will occupy more space in memory than is wasted here.

如果你ppared扔掉简单,上面code通用素质$ P $,你真的要计算小数位数,Zacks的建议适用:删除初始化。这里有一个例子:

If you're prepared to throw away the simplicity and generic qualities of the above code, and you really want to count the number of decimal digits, Zacks advice applies: Remove the initialisation. Here's an example:

#include <stddef.h>
#include <stdio.h>

size_t digit_count(int num) {
    return snprintf(NULL, 0, "%d", num) + 1;
}

int main(void) {
    int number = 32767;
    char buffer[digit_count(number)]; /* Erroneous initialisation removed as per Zacks advice */
    sprintf(buffer, "%d", number);
}


在回应的malloc 建议:解决这个问题的最可怕的方式是为了避免不必要的code(如调用的malloc 后来就免费)。如果您不必从一个函数返回的对象,那么就不要使用的malloc !否则,可以考虑存储到被调用者(通过参数)提供了一个缓冲区,使主叫方可以选择使用哪种类型的存储。这是非常罕见的,这不是用的malloc


In response to the malloc recommendations: The least horrible way to solve this problem is to avoid unnecessary code (eg. calls to malloc and later on free). If you don't have to return the object from a function, then don't use malloc! Otherwise, consider storing into a buffer provided by the caller (via arguments) so that the caller can choose which type of storage to use. It's very rare that this isn't an appropriate alternative to using malloc.

如果你决定使用的malloc 免费对于这一点,但是,做到这一点是最可怕的方式。避免对sizeof的的malloc 和乘法的返回值的类型转换由(字符)(它总是1)。下面code是一个例子。使用两种以上的方法来计算长度:

If you do decide to use malloc and free for this, however, do it the least horrible way. Avoid typecasts on the return value of malloc and multiplications by sizeof (char) (which is always 1). The following code is an example. Use either of the above methods to calculate the length:

char *buffer = malloc(digit_count(number)); /* Initialisation of malloc bytes not possible */
sprintf(buffer, "%d", number);

...不要忘了免费(缓冲); 当你用它做

这篇关于创建使用数字作为大小整数字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆