Confusing values when copying to another array

2019-09-18 01:49发布

问题:

I am trying to copy values from one array to another in C. The original array is of type long int, and it is inputted to the function as *pixel_frequency. The array I want to copy to is temp, and it is a 2D array. However, when I try to copy the values, pixel_frequency is fine but temp gives strange results. Below is the relevant code and some sample output.

Code:

struct node *generate_nodes(long int *pixel_frequency) {
    int i;
    int temp[max_value + 1][2];

    for (i = 0; i < (max_value + 1); i++) {
        temp[i][0] = i;
        temp[i][1] = pixel_frequency[i];
        printf("Frequency for %d is %d\n", temp[i][0], temp[i][1]);
    }
...

Output (each frequency is supposed to be 256):

Frequency for 0 is 150160
Frequency for 1 is 256
Frequency for 2 is 256
Frequency for 3 is 256
Frequency for 4 is 255
...
Frequency for 254 is 892677956
Frequency for 255 is 1868789101

回答1:

Below is an example version of code using your code snippet, take care of the return type and other things.

Instead of using a global variable for array size, you can pass it as a function argument so , it will be easy to identify the size of array you passed.

void generate_nodes(long int *pixel_frequency, size_t size) {
    size_t i;
    long int temp[size][2];
    for (i = 0; i < size; i++) {
        temp[i][0] = i;
        temp[i][1] = pixel_frequency[i];
        printf("Frequency for %ld is %ld\n", temp[i][0], temp[i][1]);
    }
}

If you have declared pixel_frequency as a local variable in a function and used the address of array after the variable went out of scope, will lead to undefined behaviour.

int main(void) {
    size_t max_len = 5000;
    size_t i;
    long int* pixel_frequency = malloc(max_len*sizeof(long int));

    for( i = 0; i < max_len; ++i) {
        pixel_frequency[i] = (i%256);
    }

    generate_nodes(pixel_frequency, max_len);
    return 0;
}