简体   繁体   中英

Assigning a value from pointer indexing

I am writing a program that needs optimization. I have a pointer of n integers and need to save them in different arrays but sharing the memory. My question is:

Is this

int* ptr = (int*)malloc(sizeof(int)*10);
int** ptr2 = (int**)malloc(sizeof(int*)*10);
for (int i = 0; i < 10; ++i) {
    ptr[i] = i;
    ptr2[i] = &ptr[i];
}

equivalent to this?

int* ptr = (int*)malloc(sizeof(int)*10);
int* ptr2 = (int*)malloc(sizeof(int)*10);
for (int i = 0; i < 10; ++i) {
    ptr[i] = i;
    ptr2[i] = ptr[i];
}

I mean, in the second case the value of *(ptr[i]) is copied into *(ptr2[i]) or ptr[i] and ptr2[i] point to the same memory address?

-- EDIT --

The reason I ask is I have a png image saved in an uint8_t* data with R, G and B pixels contiguous, so for example, for the first pixel (R, G, B) = (data[0], data[1], data[2]) , for the second pixel, (R, G, B) = (data[3], data[4], data[5]) and so on. So I need to separate the three channels by storing the values in three different arrays, for obvious reasons I want to share the memory of the values used in the data array and the ones used in the r_channel , g_channel and b_channel . So I don't know if I should declare each channel as uint8_t* or uint8_t** and assign its pixels like shown in the code snippets I posted as examples.

In the following code ptr is an array of integers(dynamically created) and is storing the values from 0 to 10, ptr2 is a integer pointer array where each element ( int * ) points to an element ( int ) of ptr.

 int* ptr = (int*)malloc(sizeof(int)*10); int** ptr2 = (int**)malloc(sizeof(int*)*10); for (int i = 0; i < 10; ++i) { ptr[i] = i; ptr2[i] = &ptr[i]; } 

The following code creates a copy of ptr in ptr2.

 int* ptr = (int*)malloc(sizeof(int)*10); int** ptr2 = (int**)malloc(sizeof(int*)*10); for (int i = 0; i < 10; ++i) { ptr[i] = i; ptr2[i] = &ptr[i]; } 

So in example 2 if the value of an element in ptr changes it won't get reflected in ptr whereas in example 1 if value in ptr changes it would automatically get reflected in prt2 since elements in ptr2 are pointing directly to ptr elements.

If you just want to access the data you can do that using pointer arithmetics eg for nth pixel R = data[3*n+0]; G = data[3*n+1]; B = data[3*n+2]; R = data[3*n+0]; G = data[3*n+1]; B = data[3*n+2];

But if you intend to store it in memory creating a copy seems more logical as it would require less space, since sizeof(uint8_t) <= sizeof(uint8_t *)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM