当我尝试从类型为void*
的函数中获取字符串时,我只得到第一个字符。
我尝试在不使用的情况下手动复制字符串strcpy()
它给了我同样的问题
struct arr {
int first
int last.
void **val;
};
//I have a function which is called
void *inspect_arr(const arr *ar, int position)
{
....
return ar->val[offset];
}
//I want to inspect the array so that I can compare the strings
int main()
{
char *str = calloc(10,sizeof(char));
char *k = *(char*)inspect_arr(...) //I have a string in the array
// strcpy(str,k); Doesn't work
strcmp(str,k); Invalid read from valgrind
//If array has an integer type then I would write my code like this:
//int a = *(int*)inspect_arr(...) but I can not do the same thing for char
}
运行程序时出现分段错误。
一个问题是第一个*
*(char*)inspect_arr(...)
。
在那里,您取消引用指针,仅获取第一个字符。相当于((char*)inspect_arr(...))[0]
.
为了使它更麻烦,然后将此单个字符分配给指针k
。这不会k
指向字符,而是指向k
对应于该字符编码值的任何地址。例如,ASCII 和字符'd'
初始化等效于
char *k = 100;