我想 malloc 结构中存在的整数指针。
如果将来我需要扩展数组,我会使用 realloc。
像这样:
typedef struct {
int *temp,count
}foo;
main()
{
foo *fake = (foo*)malloc(1*sizeof(foo));
fake.count = 0;
++(fake.count);
fake.temp = (int*)malloc((fake.count)*sizeof(int));
/* I do something */
/*now i want to realloc "temp" to ++(fake.count) */
这种做法是否正确?
++(fake.count);
fake.temp = (int*)realloc(fake.temp,(fake.count)*sizeof(int));
最佳答案
原则上是的。
但是,您应该确保您的代码在 realloc
中能够避免可能的错误,如下所示:
int * p = realloc(fake->temp, (fake->count + 1) * sizeof(int));
if (p) { fake->temp = p; ++fake->count; }
else { /* error! But fake was untouched. */ }
此外,您应该为主函数声明使用 int main(void)
。最后,您不应强制转换 malloc
或 realloc
的结果,因为 void*
可以隐式转换为任何其他对象指针。
还有一个:你的编码风格真的很难让人阅读。我会这样写结构定义:
typedef struct foo_
{
int * temp;
int count;
} foo;
还有一个:你需要动态分配fake
吗?如果没有,自动变量 foo fake;
可能更容易维护。无论如何,如果您确实想动态分配它,请不要强制转换也不要重复类型,如下所示:
foo * fake = malloc(sizeof *fake);
// or: calloc(1, sizeof *fake); // this will zero out the memory
关于c - 结构中存在的 realloc int 指针 [C],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11747005/