简体   繁体   中英

Memcpy from a double pointer in c

I have a pointer A , which is passed into a function with address, say myfunc(&A) .

In the function myfunc(char **A) { I want to copy memory from A[2 to n] to C[2 to n] }

I tried memcpy(&c[2], &(*A)[2], 20); I am getting the address copied into c rather than the actual info in A .

To copy memory from A[2 to n] to C[2 to n] (from question)

A is a char ** , it points to a number of char * .
The 3rd char * is A[2] . You want to use the address of that element in memcpy .
So the line should be

memcpy(&c[2], &A[2], N); 

where N is, according to your text, (n-2+1)*sizeof(char *) . memcpy size argument ignores the type of what it copies, therefore the total size of what to be copied is to be provided. You want to copy from 2 to n , that makes n-2+1 elements. Each element is a char * which size is sizeof(char *) .

-- following comment --

While not clear from the question, if you want to dereference A twice, you copy characters... like

memcpy(&c[2], &A[0][2], 20 /* 20 chars */); 

C would be a char * .

memcpy(c+2, *A+2, 20) should be enough.

Here is a test program:

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

char c[10] = { 'a', 'b' };

void myfunc(char **A)
{
    memcpy(c+2, *A+2, 8);
}

int
main(void)
{
    char *A = "ABCDEFIJK";
    printf("Before: %s\n", c);
    myfunc(&A);
    printf("After : %s\n", c);
    return 0;
}

Run:

$ ./a.out 
Before: ab
After : abCDEFIJK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM