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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With