对于字符数组的内存分配 [英] Memory allocation for char array

查看:140
本文介绍了对于字符数组的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有C语言的一个大问题,当涉及到字符串的或任何...因此,在这种特殊情况下的char * 我有一个巨大的问题。我想创建字符数组,我还不知道它会是什么尺寸。我想写的东西是这样的:

 字符测试[];

不过,在那之后,我就知道有多少元素会出现,我想写的东西是这样的:

 字符测试[num_of_elements]

虽然我知道这是错误的,我将无法做到这一点。所以,我该怎么办呢?我怎样才能宣布数组,然后确定它的大小?


解决方案

  

我怎样才能宣布数组,然后确定它的大小?


不要; '宣布'它时,你知道它需要什么尺寸。在此之前反正你不能使用它。

在C99和更高版本,可以在需要的时候定义变量 - 在一个语句块的任何地方。您还可以使用沃拉斯(变长数组),其中大小是不知道,直到运行时。不要创造出巨大的数组作为沃拉斯(例如1 MIB以上 - 但调整的限制,以满足您的机器和prejudices);使用毕竟动态内存分配。

如果你坚持古老C89 / C90的标准,那么你只能在一个块的开始定义变量和数组在编译时已知的大小,所以你必须使用动态内存分配 - 的malloc()免费()等。

I have a big problem with C language when it comes to strings, char * 's or whatever... So in this particular case I have a huge problem. I want to create an array of chars and I don't know yet what size it will be. I want to write something like this:

char test[];

But, after that, when I will know how many elements there will be, I want to write something like this:

char test[num_of_elements];

though I know it's wrong and that I wouldn't be able to do that. So, how can I do this? How can I announce the array and then define it's size?

解决方案

How can I announce the array and then define it's size?

Don't; 'announce' it when you know what size it needs to be. You can't use it before then anyway.

In C99 and later, you can define variables when needed — anywhere in a statement block. You can also use VLAs (variable-length arrays) where the size is not known until runtime. Don't create enormous arrays as VLAs (e.g. 1 MiB or more — but tune the limit to suit your machine and prejudices); use dynamic memory allocation after all.

If you're stuck with the archaic C89/C90 standard, then you can only define variables at the start of a block, and arrays have sizes known at compile time, so you have to use dynamic memory allocation — malloc(), free() etc.

这篇关于对于字符数组的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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