![](/img/trans.png)
[英]Cannot assign values to a struct pointer, after pointer was successfully assigned
[英]Cannot assign values to struct members
我动态分配了一个表示一系列点的结构数组。 但是,当我尝试为其成员分配值时,程序会分配不同的值。 我究竟做错了什么?
计划的输出:
xy[0].x= 0
xy[0].y= 0
xy[1].x= 1
xy[1].y= 1
xy[2].x= 2
xy[2].y= 2
xy[3].x= 1041
xy[3].y= 0
码:
#include <stdio.h>
#include <stdlib.h>
int n;
struct point{
int x,y;
};
typedef struct point Point;
void resize(Point*xy)
{
xy=(Point*)realloc(xy,sizeof(Point));
for (n=0;n<4;n++)
{
xy[n].x=n;
xy[n].y=n;
}
}
int main ()
{
Point *xy;
xy=(Point*)malloc(2*sizeof(Point));
for (n=0;n<2;n++){
xy[n].x=n;
xy[n].y=n;
}
resize(xy) ;
for (n = 0; n<4; n++) {
printf("xy[%i].x= %i \n",n,xy[n].x);
printf("xy[%i].y= %i \n",n,xy[n].y);
}
free(xy);
return 0;
}
我究竟做错了什么?
问题是,当您重新分配 xy
int resize()
函数的resize()
,您没有分配足够的内存:
void resize(Point*xy) { xy = (Point*) realloc( xy, sizeof(Point));
这里, realloc(xy,sizeof(Point));
仅为1
结构分配内存,因此您只能访问xy[0].x
和xy[0].y
但是,在for循环中你可以访问xy[1]
, xy[2]
和xy[3]
......这就是
访问越界 ,这会导致未定义的行为
因此,您得到未定义的输出。
方案:
使用
realloc()
分配足够的内存
当你迭代for循环4
(n = 0到3)次时,我想你需要为4
结构分配内存
只需将4乘以resize()
函数中realloc()
的第二个参数即可
xy = (Point*)realloc( xy, 4*sizeof(Point)); //multiply with 4
这里分配足够的内存来存储4
结构
输出:( 更改后)
xy[0].x= 0
xy[0].y= 0
xy[1].x= 1
xy[1].y= 1
xy[2].x= 2
xy[2].y= 2
xy[3].x= 3
xy[3].y= 3
意见建议:
首先,
不要 投的值malloc()
和 realloc()
因为它们返回void
类型,它会自动转换成它变得分配到指针的数据类型。
而不是:
xy = (Point*)realloc(xy,4*sizeof(Point)); //same for malloc dont cast
采用
xy= realloc(xy,4*sizeof(Point));
如需进一步阅读,请参阅: 点击
接着,
int main()
,而是使用int main(void)
因为没有参数被发送到main()
函数。但是,在第一种情况下是int main()
,任何数量的参数都可以发送到main()
功能...... 调整大小功能有两个问题:
void resize(Point*xy) {
xy=(Point*)realloc(xy,sizeof(Point)); // changes local variable
for (n=0;n<4;n++)
{
xy[n].x=n;
xy[n].y=n;
}
}
首先,将分配的大小从2*sizeof(Point)
缩小到sizeof(Point)
。 realloc
的第二个参数是分配的新总大小,而不是您想要添加多少。
其次,您的函数只修改局部变量xy
,它不返回它或使调用者知道。 主要:
// imagine xy = 0x10000.
resize(xy) ; // frees 0x10000 and allocates new memory
// xy here is still 0x10000
您需要在调整大小时使用Point**
指针,或者需要调整大小以返回其本地xy值:
Point* resize(Point*xy) {
int n;
xy=(Point*)realloc(xy, 4*sizeof(Point));
for (n=0;n<4;n++)
{
xy[n].x=n;
xy[n].y=n;
}
return xy;
}
要么
void resize(Point** xyp) {
int n;
*xyp=(Point*)realloc(*xyp, 4*sizeof(Point));
for (n=0;n<4;n++)
{
(*xyp)[n].x=n;
(*xyp)[n].y=n;
}
}
例:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int x, y;
} Point;
void resize(Point** xyp) {
int n;
*xyp=(Point*)realloc(*xyp, 4*sizeof(Point));
for (n=0;n<4;n++)
{
(*xyp)[n].x=n;
(*xyp)[n].y=n;
}
}
int main () {
int n;
Point *xy;
xy=(Point*)malloc(2*sizeof(Point));
for (n=0;n<2;n++)
{
xy[n].x=n;
xy[n].y=n;
}
resize(&xy) ;
for (n = 0; n<4; n++) {
printf("xy[%i].x= %i \n",n,xy[n].x);
printf("xy[%i].y= %i \n",n,xy[n].y);
}
free(xy);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.