知道指针指向的有效元素大小的方法是什么?

qwr*_*qwr 2 c

如果我想打印出存储在"数组"中的整数,这确实是内存中的指针.当我使用代码时:

int main(void)
{
  int *arr = malloc(3*sizeof(int));
  int *p = arr;
  *arr++=1;
  *arr++=2;
  *arr=3;

  while (??)           // what should be filled in the while?
    printf("%d",*p);   // so that we can get the validly stored elements?

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

C没有提供内置的方法来查找动态分配的内存块的大小.您必须存储大小,并将其"传递到侧面".

解决此问题的一种方法是创建struct组合指针和size_t描述数组中分配的元素数量的值.