简体   繁体   English

双指针上的memset操作

[英]memset operation on double pointer

Question is relevant. 问题是相关的。

For the below representation, 对于以下表示,

  typedef struct List{

    void **array; // array of void*
    int lastItemPosition;
    int size;
  }List;

  #define INITIAL_LIST_SIZE 50

createList performs as shown below, createList执行如下所示,

List *createList(List *list, Op opType){

  List *lptr = (List *)malloc(sizeof(List));

  if(opType == CREATE_NEW_LIST){

    lptr->array = malloc(INITIAL_LIST_SIZE*sizeof(void*));
    lptr->array = memset(lptr->array, NULL, INITIAL_LIST_SIZE*sizeof(void *));
    lptr->lastItemPosition = -1;
    lptr->size = INITIAL_LIST_SIZE;
}

Is memset performing valid operation on lptr->array ? memset是否在lptr->array上执行有效操作?

In your code, 在您的代码中

 memset(lptr->array, NULL, INITIAL_LIST_SIZE*sizeof(void *));

is wrong, as the second argument is expected to be an int , you're passing a pointer. 是错误的,因为第二个参数应该是int ,所以您传递了一个指针。 The conversion is a highly implementation defined behaviour, and in most of the cases, it would invoke UB. 转换是高度实现定义的行为,在大多数情况下,它将调用UB。

Related, quoting C11 , chapter §7.19 相关内容,引用C11 ,第§7.19章

NULL
which expands to an implementation-defined null pointer constant; 扩展为实现定义的空指针常量; [...] [...]

and, chapter §6.3.2.3 以及第6.3.2.3节

An integer constant expression with the value 0, or such an expression cast to type void * , is called a null pointer constant . 值为0的整数常量表达式,或强制类型为void *的表达式,称为null pointer constant

So, NULL is of pointer type which is not the compatible type to an int in any ways. 因此, NULL是指针类型,无论如何都不是与int兼容的类型。

It's valid on all major platforms, except for one thing: Don't pass NULL as the value to set. 它在所有主要平台上均有效,除了以下几点:不传递NULL作为要设置的值。 Remember that the memset function operates on the individual bytes of the memory, and you should set all the bytes to zero ( 0 ). 请记住, memset函数对内存的各个字节进行操作,并且应将所有字节设置为零( 0 )。

It is however not strictly technically valid. 但是,从技术上讲,它不是严格有效的。 On most major platforms a null pointer is equal to zero. 在大多数主要平台上,空指针等于零。 But it doesn't have to be that. 但这不是必须的。 The only fully portable and safe way to do it is through a manual loop where you set each pointer explicitly to NULL . 唯一完全可移植且安全的方法是通过手动循环将每个指针显式设置为NULL


And if anyone is interested to know, even if NULL is defined as 0 (or ((void *) 0) ) it doesn't matter. 而且,如果有人有兴趣知道,即使将NULL定义为0 (或((void *) 0) )也没关系。 The compiler will translate that zero into the platform-specific version of a null pointer, which may be something else than the actual integer zero. 编译器会将那个零转换为空指针的特定于平台的版本,这可能不是实际的整数零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM