将int数组分配给struct中的in指针

时间:2019-02-08 10:20:12

标签: c

我已经在C结构下创建了

typedef struct KnightsMartSale {
char firstName[21];
char lastName[21];
int numItemsOnList;
int *itemsPurchased; // array of item numbers
struct KnightsMartSale *next;
} KMSale;

是否可以将int数组分配给 int *购买的商品指针? 如果可能,如何打印值?

3 个答案:

答案 0 :(得分:4)

我将根据要复制到itemsPurchased中的数组的大小分配内存,并“记住” numItemsOnList中可能的项数。

因此,假设您有一个给定的整数数组,例如myArray,那么用于复制和打印的代码如下所示:

typedef struct KnightsMartSale {
    char firstName[21];
    char lastName[21];
    int numItemsOnList;
    int *itemsPurchased; // array of item numbers
    struct KnightsMartSale *next;
} KMSale;

int main() {

    KMSale kmsale;

    int myArray[] = { 20,30,40,50 };

    kmsale.numItemsOnList = sizeof(myArray)/sizeof(myArray[0]);
    kmsale.itemsPurchased = calloc(kmsale.numItemsOnList,sizeof(int));
    memcpy(kmsale.itemsPurchased,myArray,kmsale.numItemsOnList*sizeof(int));

    for (int i=0; i<kmsale.numItemsOnList; i++) {
        printf("item #%d: %d\n",i,kmsale.itemsPurchased[i]);
    }


    // kmsale not needed any more, free memory:
    free(kmsale.itemsPurchased);
}

输出:

item #0: 20
item #1: 30
item #2: 40
item #3: 50

答案 1 :(得分:0)

只需一些快速的原型编码...也许可以将您引向正确的方向...

KMSale foo; // sample struct on stack, not initialized!
int my_buffer[12]; // not initialized stack buffer!

/* Assign pointer */
foo.itemsPurchased = my_buffer; // point to my_buffer

/* Print the first element via the struct... */
printf("%02x", foo.itemsPurchased[0]);

答案 2 :(得分:0)

  

在这里可以将int数组分配给int * items购买的指针吗?如果可能,如何打印值?

是的,我们可以将数组分配给指针,因为数组是常量指针,而反向是无效的。

但是应非常谨慎地使用此分配,因为数组将是一个堆栈变量,并且在访问此结构指针之前应注意变量的范围

此方法也比动态内存分配更可取,因为动态内存分配是malloc和free关心的内存碎片问题,我们可以避免动态分配开销。

以下是此代码以及在数组中输出打印值的代码:

.join()

输出:

#include <stdio.h>

typedef struct KnightsMartSale {
    char firstName[21];
    char lastName[21];
    int numItemsOnList;
    int *itemsPurchased; // array of item numbers
    struct KnightsMartSale *next;
} KMSale;

int main() {

    KMSale sale;
    int iPos = 0;

    int Array[] = {1, 2, 3, 4, 5};

    sale.numItemsOnList = sizeof(Array) / sizeof(Array[0]);
    sale.itemsPurchased = Array;

    for (iPos=0; iPos < sale.numItemsOnList; iPos++) {
        printf("sale %d: %d\n", iPos, sale.itemsPurchased[iPos]);
    }

    return 0;
}
相关问题