arrays - 如何创建具有值的指针
问题描述
我目前正在尝试创建一个指向数组(在 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 的元素中,这与我预期的打印值不同。我不确定我哪里出错了,如果有人可以提供一些指导,我将不胜感激。
解决方案
问题是以下两行:
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);
推荐阅读
- amazon-web-services - AWS SQL Server RDS 命令超时问题
- excel - 如何计算每行中的匹配项与另一行中的值?
- amazon-web-services - 如何使用 python 代码检查 AWS 粘合作业状态?
- distributed-computing - 在 n=3f+1 个副本之间达成共识后,为什么客户端只需要查看具有相同内容的 f+1 个消息?
- flutter - Can't able to maintain the drawer state in flutter
- azure - Azure Bot Framework 与 Cosmos DB 集成中 autofac.webapi2 的用途是什么
- c# - 无法绑定 jqGrid 列
- bootstrap-table - BootstrapTable 中的格式化程序与 lit-html 不兼容
- java - 在 Spring Boot 中收到两个响应后如何并行调用 2 External API 并执行合并
- powershell - 如何在powershell http post请求中将jenkins凭据参数作为身份验证标头传递