繁体   English   中英

有什么方法可以将字符串的长度应用于 C 语言中的数组的大小?

[英]Is there any way to apply a length of a string to a size of an array in C language?

我有一个字符串x和一个数组x_integer 字符串x的长度为8 ,但是当我使用长度初始化数组int x_integer[strlen(x)] = {0} ,它不允许我这样做,因为它需要常量值。 那么无论如何我可以获取字符串x的长度并将其用于数组,除了使用#define SIZE 8导致我的字符串每次都更改。

无法初始化 VLA。

首先在定义内的下标运算符内使用strlen

int x_integer[strlen(x)];

然后,如果需要,您需要自行初始化x_integer每个元素:

int len_x = strlen(x);
for ( int i = 0; i < len_x; i++ )
{
    x_integer[i] = 0;
}

测试代码(在线示例):

#include <stdio.h> 
//#include <stdlib.h> 
#include <string.h> 

int main (void) 
{  
    const char *x = "Hello"; 
    int x_integer[strlen(x)];

    int len_x = strlen(x);
    for ( int i = 0; i < len_x; i++ )
    {
        x_integer[i] = 0;
    }

    for ( int i = 0; i < len_x; i++ )
    {
        printf("%d\n", x_integer[i]);
    }   

    return 0;
}

执行:

./a.out
0
0
0
0
0

C 中无法初始化自定义/可变长度数组。

但是你总是可以使用malloc()calloc()来分配请求的内存。

对于您的用例, calloc()最适合,因为它将分配的内存设置为0

另外,在执行操作后,不要忘记进行适当的内存管理。

看看下面的实现:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){

    char* x = "test string";

    int* x_integer = (int*)calloc(strlen(x), sizeof(int));

    //Perform operation

    //Memory management
    free(x_integer);

    return 0;
}

暂无
暂无

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

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