我可以在结构中使用 "int"作为我的动态数组吗?

标签 c arrays pointers struct dynamic-arrays

一般来说,我尝试分配 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 - p2,而不是 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/

相关文章:

c - 依赖 SDL 的应用程序的 Makefile 编译严重失败

java - 在构造函数外部将元素添加到数组

java - 单独方法中的数组

c - Mallocing 二维数组,尝试打印字符串后崩溃

处理文件和链接列表时崩溃

c - C 中 shell 命令的历史命令。从哪里开始

C -- 使用循环和索引填充 char * --- 不工作

javascript - 理解 JSON 数组

php - 如何使用 proc_open() 函数通过管道传输到 PHP 进程?

c - 简单的交换功能...为什么这个不交换?