我有一个简单的结构:在一个指针访问阵列一个struct
typedef struct {
void *things;
int sizeOfThings;
} Demo;
东西旨在包含的个体“东西”的阵列,如可能的字符串或整数。 创建指向它的指针:
Demo * Create(int value) {
Demo *d = malloc(sizeof(Demo));
if (d != NULL) {
d->sizeOfThings = value;
d->things = malloc(20 * value); // We'll have a max of 20 things
}
}
value
为整数的数组,例如的sizeof(int)的。
如果在其他功能我想插入东西放到D->的东西(假设不是,我只是将它添加到第一槽至少,位置管理做过的):
char * thing = "Me!";
strncpy(d->things[0], &thing, d->sizeOfThings);
我避开strncpy区域
test.c:10: warning: pointer of type ‘void *’ used in arithmetic
test.c:10: warning: dereferencing ‘void *’ pointer
test.c:10: error: invalid use of void expression
我只是想了解使用void *作为推广我的函数的一种方法。我怀疑d->things[0]
有什么问题。
这很有帮助。我会使用指针算术来强化未来项目吗? – Rio 2011-04-22 01:45:55
你说得对。但在这种情况下,它是“sizeof(void *)”,而不是“sizeof(void)”。 – shinkou 2011-04-22 01:50:23
我不确定你的意思。 Strncpy会复制一个字符串(这只是一个字符数组)。如果你想在一个大缓冲区中将多个stings连接在一起,你可以在偏移指针上使用strncpy,但是使用strncat会更容易。 – 2011-04-22 01:52:34