[英]Why don't my struct and array work?
我的config.h中有這個struct
和功能:
typedef struct {
char *key;
char *value;
} configParam;
void loadSettings(char fileName[], struct configParam *paramsReaded[], int *length, int *statusCode){
int i;
for(i=0; i< *length; i++){
//I try with strcpy(paramsReaded[i]->key,"key_from_txt"); and neither work :/
strcpy(paramsReaded[i].key,"key_from_txt"); // HERE DONT WORK
strcpy(paramsReaded[i].value,"value_from_txt"); // HERE DONT WORK
}
}
void initialization(configParam *paramsReaded){
paramsReaded->key = (char *)malloc(sizeof(char));
paramsReaded->value = (char *)malloc(sizeof(char));
}
在main.c中調用函數和變量:
int main()
{ //here parameters for loadsettings and the array type "configParam"
configParam *parametersReaded[];
inicializacion(¶metersReaded);
char ruta[] = "config.txt";
int length = 5;
int statusCodeee;
loadSettings(ruta,¶metersReaded,&length,&statusCodeee);
getchar();
return 0;
}
我已經以各種方式嘗試過strcpy
,但是現在我認為main.c的初始化調用中可能存在問題。 有任何想法嗎?
您遇到的主要問題是,您沒有為struct
本身分配空間,然后沒有為key
和value
分配足夠的內存。
此外,請始終檢查分配是否成功 。 否則,您可能會面臨未定義行為寫入未分配給您的結構的內存的風險。
最后,當您分配內存時,您有責任跟蹤它並在完成后釋放它。 這是您的代碼的簡短示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* provide some minimum size that will hold keys & values */
#define MAXS 32
typedef struct {
char *key;
char *value;
} configParam;
void loadSettings(char *fileName, configParam *paramsReaded, int *length, int *statusCode)
{
strcpy (paramsReaded->key,"key_from_txt"); /* or just use strdup and do away */
strcpy (paramsReaded->value,"value_from_txt"); /* with your initialization */
}
void initialization(configParam *paramsReaded)
{
paramsReaded->key = malloc (MAXS * sizeof (char));
paramsReaded->value = malloc (MAXS * sizeof (char));
/* always check your allocation succeeded */
if (!paramsReaded->key || !paramsReaded->value) {
fprintf (stderr, "error: memory allocation failed.\n");
exit (EXIT_FAILURE);
}
}
int main()
{
configParam *parametersReaded = malloc (sizeof *parametersReaded); /* allocate at least 1 */
/* always check your allocation succeeded */
if (!parametersReaded) {
fprintf (stderr, "error: memory allocation failed.\n");
return 1;
}
initialization (parametersReaded);
char ruta[] = "config.txt";
int length = 5;
int statusCodeee = 0;
loadSettings (ruta, parametersReaded,&length,&statusCodeee);
// getchar();
printf ("\n key : %s\n value: %s\n\n", parametersReaded->key, parametersReaded->value);
/* free allocated memory (note: checks are not required
if you insure your pointers have not been freed earlier
in your code.) A simple free (pointer) will suffice. */
if (parametersReaded->key) free (parametersReaded->key);
if (parametersReaded->value) free (parametersReaded->value);
if (parametersReaded) free (parametersReaded);
return 0;
}
產量
$ ./bin/initstruct
key : key_from_txt
value: value_from_txt
注意:不投結果malloc
。 它只是很難發現錯誤。 paramsReaded->key = malloc (MAXS * sizeof (char));
足夠了。
檢查內存泄漏/錯誤
如果您剛剛開始動態分配內存,請確保使用內存檢查器(例如valgrind
或Windows上的類似工具)確認內存使用情況。 它們易於使用,只需通過它們運行代碼即可。 他們將確認您的內存讀取和寫入不涉及錯誤(寫入超出分配的空間),並確認您已充分釋放分配的所有內存:
$ valgrind ./bin/initstruct
==6475== Memcheck, a memory error detector
==6475== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==6475== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==6475== Command: ./bin/initstruct
==6475==
key : key_from_txt
value: value_from_txt
==6475==
==6475== HEAP SUMMARY:
==6475== in use at exit: 0 bytes in 0 blocks
==6475== total heap usage: 3 allocs, 3 frees, 80 bytes allocated
==6475==
==6475== All heap blocks were freed -- no leaks are possible
==6475==
==6475== For counts of detected and suppressed errors, rerun with: -v
==6475== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
當你寫
paramsReaded->key = (char *)malloc(sizeof(char));
您正在分配一個字節的內存,而這不足以包含整個字符串:
strcpy(paramsReaded[i].key,"key_from_txt");
而是分配足夠的字節(即字符數+ 1)來容納結尾的0
paramsReaded->key = (char *)malloc(strlen("key_from_txt")+1);
還要注意,您似乎想要一個結構數組,因此您需要對每個結構重復以上操作。
for(i=0; i< *length; i++)
{
strcpy(paramsReaded[i].key = strdup(yourkey);
strcpy(paramsReaded[i].value = strdup(yourvalue);
}
yourkey和yourvalue是您要復制的任何文本(strdup與malloc + strcpy相同)
除了CyberSpock的答案,我注意到的另一件事是
configParam *parametersReaded[];
如果在聲明時不初始化它們,則需要給出數組元素的數量(這是一般的C概念)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.