复制到另一个阵列时混淆值 [英] Confusing values when copying to another array

查看:134
本文介绍了复制到另一个阵列时混淆值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C中将值从一个数组复制到另一个数组。原始数组的类型为 long int ,并且它作为<$ c输入到函数中$ C> * pixel_frequency 。我要复制的数组是 temp ,它是一个2D数组。但是,当我尝试复制值时, pixel_frequency 很好,但 temp 会产生奇怪的结果。以下是相关代码和一些示例输出。

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.

代码:

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]);
    }
...

输出(每个频率应为256 ):

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


推荐答案

以下是使用您的代码片段的代码示例版本,负责返回类型和其他的东西。

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]);
    }
}

如果您已声明 pixel_frequency 作为函数中的局部变量,并在变量超出范围后使用数组的地址,将导致未定义的行为。

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;
}

这篇关于复制到另一个阵列时混淆值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆