kevin
kevin

Reputation: 14095

How to put data from a buffer to an array in C?

I have got some data in a buffer and want to put those data in an array.

 typedef struct chunk 
 {
 char data[300];    /* the bufferr. */
 } CHUNK;
 char *buffer, CHUNK c [100];

Assuming I have got data into the buffer, how can I put 300 char per chunk? I'm new to C so please explain me with simple example.

Thanks, Kevin

Upvotes: 3

Views: 18409

Answers (3)

Alok Singhal
Alok Singhal

Reputation: 96181

In C, you can copy memory from one area to another using memcpy(). The prototype for memcpy() is:

void *memcpy(void *dst, const void *src, size_t n);

and the description is that it copies n bytes from src to dst, and returns dst.

So, to copy 300 bytes from b to a where both a and b point to something useful, b has at least 300 bytes of data, and a points to at least 300 bytes of space you can write to, you would do:

memcpy(a, b, 300);

Now your task should be something along the lines of:

typedef struct chunk 
{
    char data[300];
} CHUNK;
char *buffer;
CHUNK c[100];
size_t i;

/* make buffer point to useful data, and then: */
for (i=0; i < 300; ++i)
    memcpy(c[i].data, buffer+i*300, 300);

Upvotes: 2

wallyk
wallyk

Reputation: 57784

The declaration is invalid, but I think you mean:

typedef struct chunk 
 {
     char data[300];    /* the bufferr. */
 } CHUNK;

 char *buffer;
 CHUNK c [100];

If I understand your question correctly (which I'm far from certain that I do), the code would be something like:

 int j = 0;
 char *bp = buffer;
 while (*bp)
 {
     strncpy (c [j] .data, bp, 300);  // copy data into next item
     bp += strlen (bp);
     ++ j;
 }

Upvotes: 3

Mahesh
Mahesh

Reputation: 34625

You can use strncpy.

strncpy( data, buffer, 299 ) ;

Leaving the last index for the termination character '\0'. Or make the array size 301 and then use strncpy for 300 elements.

Upvotes: 1

Related Questions