Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c pointers and arrays, copying contents into another array

Tags:

arrays

c

pointers

I know this is probably a basic question, but i've never fully grasped the whole pointers concept in C.

My question is, say i have an int array and I pass that into a function like `

int main(){
    int *a = malloc(sizeof(int*)*4);

    // add values to a
    p(a);
}

void p(int *a){
   int *b = malloc(sizeof(int*)*4)
   b = a;
   // change values in b

   //print a b
}`

What is the correct way to do this so that whatever changes I make to b do not affect the values in a?

like image 269
cHam Avatar asked Apr 10 '14 00:04

cHam


1 Answers

In your 'p' method, you're assigning pointer b to be pointer a, or, in otherwords, you're making b point to what a points to. Any changes to b will cause changes to a since they both wind up pointing to the same block of memory.

Use memcpy to copy blocks of memory. It would look something like this:

#include <string.h>
#include <stdlib.h>
void p(int *a){
   int *b = (int*)malloc(sizeof(int)*4);
   memcpy(b, a, sizeof(int)*4);

    //make changes to b.
   b[0] = 6;
   b[1] = 7;
   b[2] = 8;
   b[3] = 9;
}

int main(int argc, char **argv)
{
    int *a = (int*)malloc(sizeof(int)*4);

    // add values to a
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    a[3] = 4;

    p(a);

return 0;
}
like image 96
Brandon Haston Avatar answered Sep 20 '22 13:09

Brandon Haston