Khang Nguyen
Khang Nguyen

Reputation: 17

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

I have a string x and an array x_integer. String x has a length of 8, but when I use the length to initialize the array int x_integer[strlen(x)] = {0}, it doesn't allow me to do that since it needs constant value. So are there anyways that I can take the length of string x and use that for the array besides using #define SIZE 8 cause my string changes each time.

Upvotes: 1

Views: 76

Answers (2)

VLAs can't be initialized.

Use strlen inside of the subscript operator inside of the definition first:

int x_integer[strlen(x)];

and then, if wanted, you need to initialize each element of x_integer on its own:

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

Test code (Online example):

#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;
}

Execution:

./a.out
0
0
0
0
0

Upvotes: 2

Deepak Tatyaji Ahire
Deepak Tatyaji Ahire

Reputation: 5311

There is no way in C to initialise the custom/variable length arrays.

But you can always make use of malloc() and calloc() to allocate the requested memory.

For your use case, calloc() fits the best as it sets the allocated memory to 0.

Also, after performing operations, don't forget to carry out a proper memory management.

Have a look at the following implementation:

#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;
}

Upvotes: 2

Related Questions