简体   繁体   English

C中没有固定大小的字符数组

[英]Array of characters in C without fixed size

How can an array of characters be entered without using a fixed length array in C? 如何在不使用C中的固定长度数组的情况下输入字符数组? I was given an assignment to center strings in C, and was told not to use a fixed size array. 我被赋予C中心字符串的赋值,并被告知不要使用固定大小的数组。

The only way to create an array without a fixed size is by using malloc , which accepts the size (in bytes) of memory you want to allocate. 创建没有固定大小的数组的唯一方法是使用malloc ,它接受要分配的内存大小(以字节为单位)。 You will then use it as a char* , which can also accomodate array syntax. 然后,您将使用它作为char* ,它也可以容纳数组语法。 Do not forget to test that the return value is nonzero (which is the way malloc indicates that you are out of memory). 不要忘记测试返回值是非零(这是malloc指示您内存不足的方式)。

After you are done using the memory, you are then responsible for releasing it back to the system with free . 使用完内存后,您将负责将其free释放回系统。

For example: 例如:

size_t size = 42; // you can read this from user input or any other source
char* str = malloc(size);

if (str == 0) {
    printf( "Insufficient memory available\n" );
}
else {
    // Use the memory and then...
    free(str);
}

Look up the functionality of malloc and realloc . 查找mallocrealloc的功能。

I assume non-fixed size means dynamically allocated array - which can be obtained using malloc . 我假设非固定大小意味着动态分配的数组 - 可以使用malloc获得。

You can do dynamic memory allocation by malloc . 您可以通过malloc进行动态内存分配

Example : 示例

int main()
{
    int i;

    printf ("How long do you want the string? ");
    scanf ("%d", &i);

    char *buffer = malloc (i+1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM