说我是否要打印出存储在“数组”中的整数,这确实是内存中的指针。当我使用代码时:
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;
}
答案 0 :(得分:5)
C没有提供内置的方法来查找动态分配的内存块的大小。你必须存储大小,并将其传递给“侧面”。
解决此问题的一种方法是创建一个struct
组合指针和一个size_t
值,用于描述数组中分配的元素数量。