What's the fastest way to get a slice of an array in c?
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
source to share
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.
source to share