我的函数需要一个void *缓冲区,并且必须用char * buffer_rep内部的内容填充它。但是当我写这篇文章时:
int function(void *buffer, int size)
{
char buffer_rep[512];
// my buffer_rep is filled up with the call of another function.
// It is not empty
for (int i = 0; i < size; i++) { // size is below 512
buffer[i] = buffer_rep[i];
}
return 0;
}
for表达式内的行给我错误“无效使用void表达式”。如果我尝试像这样投射缓冲区:
(char *)buffer[i] = buffer_rep[i];
我收到相同的错误,并显示警告“无效的类型转换”。我也尝试用(char)代替(char *)。 我在C语言方面没有太多经验,我尝试自己寻找解决方案,但通常人们在投射时不会出现此错误。我认为有些明显的东西我看不到。
答案 0 :(得分:1)
您必须强制转换指针,但是强制转换的问题是您强制转换了 element 而不是指针。即表达式(char *)buffer[i]
等于(char *)(buffer[i])
。
如果在正确的位置使用括号,应该没问题:((char *)buffer)[i]
答案 1 :(得分:1)
您必须将强制转换应用于null: Array(1) [Object]
length: 1
__proto__: Array(0) [, …]
0: Object {fantasypoints: 324.15, players: Array(8), salary: 48800}
fantasypoints: 324.15
players: Array(8) [Object, Object, Object, …]
length: 8
__proto__: Array(0) [, …]
0: Object {_max_exposure: null, _projected_ownership: null, first_name: "Ray", …}
1: Object {_max_exposure: null, _projected_ownership: null, first_name: "Clearlove", …}
2: Object {_max_exposure: null, _projected_ownership: null, first_name: "Scout", …}
3: Object {_max_exposure: null, _projected_ownership: null, first_name: "Hope", …}
4: Object {_max_exposure: null, _projected_ownership: null, first_name: "Meiko", …}
5: Object {_max_exposure: null, _projected_ownership: null, first_name: "SnowFlower", …}
6: Object {_max_exposure: null, _projected_ownership: null, first_name: "Arce", …}
7: Object {_max_exposure: null, _projected_ownership: null, first_name: "Infinity eSports", …}
salary: 48800
__proto__: Object {constructor: , __defineGetter__: , __defineSetter__: , …}
,而不是buffer
。
将代码更改为
buffer[i]