Libor Zapletal
Libor Zapletal

Reputation: 14102

C - get chars from part of byte array

How can I get char array or char pointer from part of byte array? Let´s say I have variable-size string in byte array which begins at 18 bytes and ends 4 bytes from end of array. How can I get this?

Edit: And what about dot? I should have dots in that byte array but when I copied by memcpy I get string without dots. How can I fix this?

Upvotes: 3

Views: 3908

Answers (4)

dsgdfg
dsgdfg

Reputation: 1520

memcpy(destination, source, count);

  • Destination = Storage Area (!important destination_SIZE >= count)
  • Source = Array that holds the data to be copied (Default starting index = 0, But source+n can be skip n bytes(You shouldn't be out of the source Array))
  • count = How many bytes will be copied.

A small warning: if the target is the same as the source, you must save all operands in the index.

Upvotes: 0

md5
md5

Reputation: 23709

To extract a part of an array, you can use memcpy.

#include <string.h>

char dst[4];

/* Here, we can assume `src+18` and `dst` don't overlap. */
memcpy(dst, src + 18, 4);

C11 (n1570), § 7.24.2.1 The memcpy function
The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

Upvotes: 2

Paul R
Paul R

Reputation: 212979

Well you can just use memcpy to copy any arbitrary range of bytes:

const int index1 = 18;    // start index in src
const int index2 = 252;   // end + 1 index in src

char src[256];            // source array
char dest[256];           // destination array

memcpy(dest, &src[index1], index2 - index1);
                          // copy bytes from src[index1] .. src[index2 - 1]
                          // inclusive to dest[0] .. dest[index2 - index1 - 1]

This will copy bytes from index 18 through 251 from src and store them in dest.

Upvotes: 2

Aniket Inge
Aniket Inge

Reputation: 25705

google the use of memcpy. it will satisfy your question

const char *buffer = "I AM A VERY VERY VERY VERY VERY VERY VERY VERY BIG STRING";
char buffer2[4];

memcpy(buffer2, (buffer+18), 4);

And fanny's your aunt.

Upvotes: 1

Related Questions