What's the fastest way to get a slice of an array in c?

I would like to do something like this:

char in[] = {'a','b','c','d','f','r','t','b','h','j','l','i'};

char out[3];

out = ∈

      

and get only the first 3 characters

but i get an error of incompatible types

+3


source to share


4 answers


out

is the name of the array and cannot be changed. There is no direct way to get a slice of an array in C. You can use memcpy

:

memcpy(out, in, sizeof out);

      



And you have to accept that you in

have enough elms to copy.

+8


source


Since your arrays are not designed to accommodate strings, the relevant code might look like this.

#include <stdio.h>

int main() 
{
    char in[] = {'a','b','c','d','f','r','t','b','h','j','l','i'};
    size_t n = sizeof( in );
    char out[3];

    memcpy( out, in, sizeof( out ) );
    n -= sizeof( out );
    memmove( in, in + sizeof( out ), n );

    printf( "%*.*s\n", n, n, in );
    printf( "%*.*s\n", sizeof( out ), sizeof( out ), out );

    return 0;
}

      

Program output

dfrtbhjli
abc

      

Note that you need to keep track of the actual length of the array.



Another example

#include <stdio.h>

int main() 
{
    char in[] = {'a','b','c','d','f','r','t','b','h','j','l','i'};
    size_t n = sizeof( in );
    char out[3];

    printf( "%*.*s\n\n", n, n, in );

    while ( !( n < 3 ) )
    {
        memcpy( out, in, sizeof( out ) );
        n -= sizeof( out );
        memmove( in, in + sizeof( out ), n );

        printf( "%*.*s\n", sizeof( out ), sizeof( out ), out );
    }

    return 0;
}

      

Program output

abcdfrtbhjli

abc
dfr
tbh
jli

      

+4


source


out

is an array name and an array name cannot be volatile lvalues.

Arrays are not assigned in C.

+3


source


I suggest three ways:

strncpy(out, in, sizeof out)

memcpy(out, in, sizeof out)

sscanf(in, "%3s", out)

Also, you have to make it out

static or global, or allocate it to the heap using malloc

. Just to make sure anything outside or in the first three characters won't get copied onto it.

// global
char out[3];
int main() {...

      

...

// static
static char out[3];

      

...

// heap
char *out = (char*) malloc(sizeof(char) * 3);
free(out);

      

It's up to you what to choose.

+1


source







All Articles