c - typedef'd array of pointers - copying values -
good day,
i have few simple typedefs so:
typedef int datatype; typedef datatype* arrayofnpointers[n];
so, datatype
represents int
, , type arrayofnpointers
represents array of n
pointers int
's.
am able reliably perform deep copy of contents of 1 of these arrays so:
#define n (2) arrayofnpointers a1 = { 1, 2}; arrayofnpointers a2; a2 = a1; // safe?
i know can directly copy struct's this, , know in general, if try assign int*
pointers, qualify "shallow copy".
in case, end 2 independent fixed-size arrays contain elements {1, 2}
?
thank you!
firstly, watch out:
arrayofnpointers a1 = {1, 2};
as far can tell, initialising pointers if integers. cannot end well. (i'll deal more later.)
but anyway:
safe?
nope. a1
, a2
both arrays; means that, among other things, cannot assigned to.
a2 = a1; // ^^^^ wrong
even if was possible [e.g. if pointers], wouldn't shallow copy - 2 [arrays pretending are] pointers point @ same block of memory. [only structs can shallow-copied way.]
a proper deep copy of array can performed in c for-loop:
for (int = 0; < n; ++i) { a2[i] = a1[i]; }
but you're dealing pointers, above counts shallow copy. you'll need more interesting deep-copy array:
for (int = 0; < n; ++i) { a2[i] = malloc(sizeof(int)); *a2[i] = *a1[i]; }
but what's wrong arrayofnpointers a1 = {1, 2};
?
a lot. {1, 2}
not initialising integers pointed to; initialising pointers.
fix 1
arrays of integers:
typedef datatype arrayofintegers[n]; arrayofintegers a1 = {1, 2};
fix 2
properly initialised arrays of pointers integers:
datatype arr[n] = {1, 2}; arrayofnpointers a1 = {&a[0], &a[1]};
or, if you'd use malloc
ed memory, , allocate later:
arrayofnpointers a1 = {null};
the rules of initializer lists ensure tht pointers null.
Comments
Post a Comment