Reputation: 2664
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?
Upvotes: 6
Views: 50581
Reputation: 1004
void p(int *a){
int *b = malloc(sizeof(int*)*4)
int size=4;
while(size>=0){
b[size--]=a[size--];
}
// change values in b
//print a b
}
This should work!
Upvotes: 0
Reputation: 434
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;
}
Upvotes: 7
Reputation: 11669
You are pointing a
and b
to two different blocks of memory and then assigning b
to the block pointed to by a
, causing a memory leak.
And since you are not returning anything from your function p()
, you can allocate b
on stack (I wonder what you are doing with it).
If your intention is to copy the data pointed to by these pointers, you can use memcpy
or copy element by element as others have suggested.
Upvotes: 0
Reputation: 29266
Just assigning the pointer means b
is pointing to the same chunk of memory as a
and the memory you just allocated "for b
" has leaked. It's allocated but you can't free it any more.
To copy the array you need to well, copy it.
Easy way is lookup the various memcpy
methods, or just do it the longer way
for (int i = 0; i < 4; i++) {
b[i] = a[i];
}
You need to know about "shallow copy" and "deep copy" - since you have an array of int*
, what I put above is a shallow copy. If you need to copy the contents that each int*
points to, you'll need something more complex again.
Upvotes: 1