一般来说,我尝试分配 first.a 和 first.b 的值 到数组的第二个结构中。
typedef struct {
int a;
int b;
} firs;
//secon is my struct which contains dynamic array
//can i use int here ?
typedef struct {
int *aa;
int *bb;
} secon;
//pointer to secon intialised to NULL;
secon* sp=NULL;
int main()
{
firs first;
//plz assume 2 is coming from user ;
sp=malloc(sizeof(secon)*2);
//setting values
first.a=10;
first.b=11;
/* what i'm trying to do is assign values of first.a and first.b to my
dynamically created array*/
/* plz assume first.a and first.b are changing else where .. that means ,not
all arrays will have same values */
/* in general , i'm trying to allocate values of first.a and first.b
to a array's in struct second. */
for(int i=0; i<2; i++) {
*( &(sp->aa ) + (i*4) ) = &first.a;
*( &(sp->bb ) + (i*4) ) = &first.b;
}
for(int i=0; i<2; i++) {
printf("%d %d \n", *((sp->aa) + (i*4) ),*( (sp->bb) +(i*4) ) );
}
return 0;
}
我的输出:
10 11
4196048 0
我的代码有问题: 1.我的代码有什么问题? 2. 我可以在动态数组的结构中使用 int 吗? 3.有哪些选择? 4. 为什么我得不到正确答案?
最佳答案
Grigory Rechistov 在理清代码方面做得非常出色,您可能应该接受他的回答,但我想特别强调一点。
在 C 指针算法中,偏移量总是以指向的类型的大小为单位。除非指针的类型是 char*
或 void*
如果您发现自己乘以类型的大小,几乎可以肯定您做错了。
如果我有
int a[10];
int *p = &(a[5]);
int *q = &(a[7]);
则a[6]
与*(p + 1)
相同 不是 *(p + 1 * sizeof (整数))
。同样,a[4]
是 *(p - 1)
此外,当指针都指向同一个数组中的对象并且应用相同的规则时,您可以减去指针;结果以指向的类型的大小为单位。 q - p
是 2
,而不是 2 * sizeof(int)
。将示例中的类型 int
替换为任何其他类型,p - q
将始终为 2
。例如:
struct Foo { int n ; char x[37] ; };
struct Foo a[10];
struct Foo *p = &(a[5]);
struct Foo *q = &(a[7]);
q - p
仍然是 2
。顺便说一句,永远不要试图在任何地方对类型的大小进行硬编码。如果您想要 malloc
像这样的结构:
struct Foo *r = malloc(41); // int size is 4 + 37 chars
不要。
首先,sizeof(int)
不能保证为 4。其次,即使是,sizeof(struct Foo)
也不能保证为 41。编译器通常向 struct
类型添加填充以确保成员正确对齐。在这种情况下,几乎可以肯定编译器将向 struct Foo
的末尾添加 3 个字节(或 7 个字节)的填充,以确保在数组中,n 的地址
成员与 int 的大小对齐。总是总是总是使用sizeof
。
关于我可以在结构中使用 "int"作为我的动态数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48804138/