首页 > 解决方案 > 如何创建具有值的指针

问题描述

我目前正在尝试创建一个指向数组(在 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 的元素中,这与我预期的打印值不同。我不确定我哪里出错了,如果有人可以提供一些指导,我将不胜感激。

标签: arrayscpointers

解决方案


问题是以下两行:

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

推荐阅读