【问题标题】:How to create a pointer with value如何创建具有值的指针
【发布时间】:2021-06-20 03:48:46
【问题描述】:

我目前正在尝试创建一个指向数组(在 C 中)的指针,由于我的用例,我需要通过指针操作来完成这一切。我最终想要的输出是一个 uint8_t 类型的指针,它指向一个具有我确定的值的元素数组,但这似乎不起作用。

这是我用来创建它的代码:

uint8_t* create_array_uint8(int height,int width, uint8_t value, int print_array = 0){
    int size = height*width * sizeof(uint8_t);
    uint8_t* array;
    array = (uint8_t*) malloc(size);

    int total_elements = height* width;
    int count = 0;

    uint8_t* val_ptr;
    val_ptr = array;
    while (count<total_elements){
        val_ptr = val_ptr + count * sizeof(uint8_t);
        *val_ptr = value;
        count++;
    }

    if (print_array == 1){
        int count = 0;

        uint8_t* print_ptr;
        print_ptr = array;
        while (count<total_elements){
            print_ptr = print_ptr + count * sizeof(uint8_t);
            printf("The %d element has a value of ---> %d \n",count,*print_ptr);
            count++;
        }
    }
    return array;
}

这是我在使用这个函数:

    uint8_t* A = create_array_uint8(3,3,1,1);

即我正在创建一个 uint8_t 类型的指针,它指向一个包含 9 个 uint8_t 元素的数组,其值为 1。但是我的输出如下:

root@a7b006267463:# nvcc test.cu 
root@a7b006267463:# ./a.out 
The 0 element has a value of ---> 1 
The 1 element has a value of ---> 1 
The 2 element has a value of ---> 1 
The 3 element has a value of ---> 1 
The 4 element has a value of ---> 1 
The 5 element has a value of ---> 1 
The 6 element has a value of ---> 1 
The 7 element has a value of ---> 0 
The 8 element has a value of ---> 37 

在所有值为 1 的元素中,这与我预期的打印值不同。我不确定我哪里出错了,如果有人可以提供一些指导,我将不胜感激。

【问题讨论】:

  • 对我来说这看起来像 C。为什么是 C++ 标签?
  • val_ptr 先前进一个,指向array[1]。然后是两个,指向array[3]。然后三点,指向array[6]。这继续以更大的步伐;很快,它就会越界,程序会出现未定义的行为。
  • 似乎是一个错字。应该将 count * sizeof(uint8_t) 添加到 array 而不是 val_ptrprint_ptr。或者将其保留为添加到 val_ptrprint_ptr,但添加 sizeof(uint8_t) 而不是 count * sizeof(uint8_t)。任何一种方法都有效,但不要将它们混合在一起。
  • 只是++val_ptr; 在循环结束而不是val_ptr = val_ptr + count * sizeof(uint8_t);,与print_ptr 相同

标签: arrays c pointers


【解决方案1】:

问题在于以下两行:

val_ptr = val_ptr + count * sizeof(uint8_t);
print_ptr = print_ptr + count * sizeof(uint8_t);

这两行正在访问分配的内存。

请尝试:

val_ptr = array + count * sizeof(uint8_t);
print_ptr = array + count * sizeof(uint8_t);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-03
    • 2023-03-12
    • 1970-01-01
    • 2021-07-21
    • 2021-04-05
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多