stressed_geek
stressed_geek

Reputation: 2176

Is direct assignment valid to copy a pointer from array of pointers to another variable?

I am trying to copy an array of pointers to a new variable. I am not sure if the following direct assignment is the right way to perform the copy.

SVECTOR **features = (SVECTOR **) malloc(n*sizeof(SVECTOR *));
for(i = 0; i < n; i++){
    features[i] = getFeature();
}
SVECTOR **new_features = features; // Doubt: 1
SVECTOR *feature = features[0]; // Doubt: 2 

Upvotes: 0

Views: 199

Answers (1)

Jim Balter
Jim Balter

Reputation: 16416

Attempt 1 gives you an alias -- features and new_features reference the same array. Attempt 2 gives you an alias to the first feature.

What you want, for a shallow copy (adequate if the values pointed to by the pointers returned by getFeature() are never modified or deallocated), is

SVECTOR **new_features = malloc(n * sizeof *features);
memcpy(new_features, features, n * sizeof *features);

If a shallow copy isn't adequate then you need to do a deep copy, which needs to know the structure of a feature:

SVECTOR **new_features = malloc(n * sizeof *features);
for(i = 0; i < n; i++){
    new_features[i] = cloneFeature(features[i]);
}

Upvotes: 1

Related Questions