上下文:我想做的是创建一个程序,将文本作为输入并将其存储在字符数组中。然后我会打印数组的每个元素作为小数。例如。 “Hello World”将转换为72,101等。我会将其用作快速ASCII2DEC转换器。我知道有在线转换器,但我正在尝试自己做这个。
问题:如何在编译时分配一个大小未知的数组,并使其与我输入的文本大小完全相同?因此,当我输入“Hello World”时,它将动态地生成一个具有存储“Hello World”所需的确切大小的数组。我在网上搜索过但找不到任何可以使用的东西。
答案 0 :(得分:1)
我看到你正在使用C.你可以这样做:
#define INC_SIZE 10
char *buf = (char*) malloc(INC_SIZE),*temp;
int size = INC_SIZE,len = 0;
char c;
while ((c = getchar()) != '\n') { // I assume you want to read a line of input
if (len == size) {
size += INC_SIZE;
temp = (char*) realloc(buf,size);
if (temp == NULL) {
// not enough memory probably, handle it yourself
}
buf = temp;
}
buf[len++] = c;
}
// done, note that the character array has no '\0' terminator and the length is represented by `len` variable
答案 1 :(得分:0)
通常情况下,在没有很大内存限制的PC这样的环境中,我只会动态分配(依赖于语言)数组/字符串/等等,比如64K,并保留索引/指针/其他任何内容当前终点加一 - 即。放置任何新数据的下一个索引/位置。
答案 2 :(得分:0)
如果使用cpp语言,可以使用字符串存储输入字符,并通过operator []访问字符,如下代码所示:
std::string input;
cin >> input;
答案 3 :(得分:0)
我猜你的意思是C,因为这是最常见的编译语言之一,你会遇到这个问题。
您在函数中声明的变量存储在堆栈中。这很好用,有效,在函数退出时会被清理等等。唯一的问题是每个函数的堆栈槽大小是固定的,在函数运行时不能改变。
您可以分配内存的第二个位置是堆。这是一个免费的,你可以在运行时分配和释放内存。使用malloc()进行分配,完成后,在其上调用free()(这对于避免内存泄漏非常重要)。
使用堆分配时,您必须知道分配时的大小,但它比将其存储在固定堆栈空间中更好,如果需要,您无法增长。
这是一个简单而愚蠢的功能,可以使用动态分配的缓冲区将字符串解码为ASCII码:
char* str_to_ascii_codes(char* str)
{
size_t i;
size_t str_length = strlen(str);
char* ascii_codes = malloc(str_length*4+1);
for(i = 0; i<str_length; i++)
snprintf(ascii_codes+i*4, 5, "%03d ", str[i]);
return ascii_codes;
}
编辑:您在评论中提到想要使缓冲区恰到好处。我通过将字符串中的每个条目设置为已知长度而不修剪结果的额外空格字符来使用上面的示例进行切角。这是一个更智能的版本,可以解决这两个问题:
char* str_to_ascii_codes(char* str)
{
size_t i;
int written;
size_t str_length = strlen(str), ascii_codes_length = 0;
char* ascii_codes = malloc(str_length*4+1);
for(i = 0; i<str_length; i++)
{
snprintf(ascii_codes+ascii_codes_length, 5, "%d %n", str[i], &written);
ascii_codes_length = ascii_codes_length + written;
}
/* This is intentionally one byte short, to trim the trailing space char */
ascii_codes = realloc(ascii_codes, ascii_codes_length);
/* Add new end-of-string marker */
ascii_codes[ascii_codes_length-1] = '\0';
return ascii_codes;
}