一些指针算术有相当大的麻烦.我想我得到了概念(指针变量指向内存地址,正常变量指向数据)但我相信我的问题是语法(*, &, (*), *(),
等)
我想要做的是构建一个自定义结构的动态数组(即指向堆结构的指针数组),我的接口提供两个方法,"ad_to_obj_array"(它接受要添加的对象,以及可以为null的数组为空)和"obj_array_dustbin"(它只是处理数组,也处理内容,堆objs).前者呈现如下.
对象的细节并不重要(并且结构已经被重命名)但是我对一般问题的解决方案如下,如果您能发现错误,我将不胜感激.编译器抱怨无效的左值,我尝试将RHS上的指针中的地址分配给堆结构指针数组中的指针值:
#define NUM_ELEM(x) (sizeof (x) / sizeof (*(x)))
obj* add_to_obj_array(obj* new_obj, obj* array)
{
int number_of_elements = 0;
if (array != NULL)
{
number_of_elements = NUM_ELEM(array);
}
obj* new_array = NULL;
/* note: I am expecting sizeof(new_obj) to return the size of an obj*
to go into the array of pointers. */
if ( NULL ==
(new_array = (obj*)malloc((number_of_elements + 1)* sizeof(new_obj))) )
{
/* memory request refused :( */
return …
Run Code Online (Sandbox Code Playgroud) 我在 C 语言中为我的 qsort 有这个比较器函数,但无论我尝试什么,我似乎都会遇到分段错误...
int textCompare ( const void * a, const void * b ){
const char **x =(const char**)a;
const char **y =(const char**)b;
return strcmp(*x, *y);
}
Run Code Online (Sandbox Code Playgroud)
这是我的 qsort 调用:其中message** mList = malloc(INITIAL_CAPACITY * sizeof(message));
和count
是一个跟踪最后一个元素的整数。message 只是一个 typedef 结构体,其中包含一个 int 和一个指向 char 的指针。我 67% 确信我正确调用了 qsort,有人能指出我正确的方向吗?
qsort (*mList, count, sizeof(message), textCompare);
Run Code Online (Sandbox Code Playgroud)
[编辑] 我声明 message*** 而不是 message* 的原因是因为我试图初始化指向结构的指针的“数组”;除非我以错误的方式处理这个问题?