JohnDoe
JohnDoe

Reputation: 915

get address of pointer to first element of array and copy all elements to new buffer

I'm doing the following:

Let's say I have an array:

uint8 Array[100] = {25,33,48,20,.....}; 

There exist a function which is doing the following:

void getValues(uint8 **pvalues)
{
    *pvalues =&Array[0];        //Saves the address of first element of Array[]
}

later in my code I have following:

uint8 *pmyValues;
uint8 myBuffer[100];
uint8 i=0;

getValues(&pmyValues)

for (i;i<100;i++)
{
   (void)memcpy(&myBuffer[i], (uint8*)&pmyValues[i], sizeof(uint8));        
}

I want to have the values from Array ow in my own internal buffer pmyBuffer After debugging I see that pmyBuffer is containing an array of pointers!? Not sure what I'm doing wrong? I'm new to pointers in C and would be thankful I somebody can provide help.

Thanks!

Upvotes: 1

Views: 569

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

The presented code by you in the question does not make sense. If you want to

get address of pointer to first element of array and copy all elements to new buffer

then you can just write

memcpy( myBuffer, Array, 100 * sizeof( *Array ) );

Here is a demonstrative program

#include <stdio.h>
#include <string.h>
#include <stdint.h>

int main(void) 
{
    enum { N = 10 };
    uint8_t Array[N] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
    uint8_t myBuffer[N];

    memcpy( myBuffer, Array, N * sizeof( *Array ) );

    for ( size_t i = 0; i < N; i++ )
    {
        putchar( myBuffer[i] );
    }
    putchar( '\n' );

    return 0;
}

The program output is

ABCDEFGHIJ

If by some reason you need to use an intermediate pointer then the code can look something like the following.

#include <stdio.h>
#include <string.h>
#include <stdint.h>

void getValues( uint8_t **pvalues, uint8_t Array[] )
{
    *pvalues = Array;
}

int main(void) 
{
    enum { N = 10 };
    uint8_t Array[N] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
    uint8_t myBuffer[N];

    uint8_t *pmyValues;

    getValues( &pmyValues, Array );

    memcpy( myBuffer, pmyValues, N * sizeof( *pmyValues ) );

    for ( size_t i = 0; i < N; i++ )
    {
        putchar( myBuffer[i] );
    }
    putchar( '\n' );

    return 0;
}

Upvotes: 4

Related Questions