簡體   English   中英

向結構內的數組添加數據

[英]Add data to array inside struct

如何將數據設置為3行同時包含4個元素的數組?

#include <stdio.h>
#include <stdlib.h>
#include "string.h"

typedef struct
{
    char value[6];
} MyType;

typedef struct
{
    int size;
    MyType *values;
} NewType;

static NewType car;
static MyType mytype = {{'\0'}};

void Init(NewType *car)
{
    car->size = 3; // Will contain 3 rows of 4 elements
    car->values = (MyType*) calloc(car->size,sizeof(MyType));
}

// Get data into
void Write(NewType *car, MyType *data)
{
   strcpy(car->values[0].value, data[0].value); // ** Here is where complains

   printf("%d\n", car->values[0]); // Printing wrong data!
}

int main()
{
    Init(&car);

    strcpy(mytype.value, "Hello"); 

    Write(&car, &mytype);

    system("PAUSE");
}

在這段代碼中, strcpy(mytype.value, "Hello"); 您正在將5個字母的字符串復制到4個字符的數組中,這是非法的,因此可能導致錯誤。 將您復制到mytype.value的字符串更改為較短的字符串(例如"Bye" ),或者將value char數組中的元素數量增加為要放入其中的單詞的字符數,再加上一個用於終止的字符空字符。

另外, Write()函數中的printf()語句具有一個格式字符串,該字符串指示要打印一個int ,我懷疑這是您實際想要的。 以下是重寫的Write()main()函數。

void Write(NewType *car, MyType *data)
{
   strcpy(car->values[0].value, data->value);

   printf("%s\n", car->values[0].value); 
}

int main()
{
    Init(&car);

    strcpy(mytype.value, "Bye"); 

    Write(&car, &mytype);

    system("PAUSE");
}

實際上printf("%d\\n", car->values[0])在您的printf("%d\\n", car->values[0])您嘗試打印Init()已調用的內存的前4個字節,格式為帶符號的十進制整數。 (對於x86,通常為sizeof(int) )。

要打印值,您應該:

printf("%s\n", car->values->value); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM