为什么我的结构和数组不起作用?

时间:2015-04-14 05:30:42

标签: c arrays pointers struct

我在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(&parametersReaded);
    char ruta[] = "config.txt";
    int length = 5;
    int statusCodeee;

   loadSettings(ruta,&parametersReaded,&length,&statusCodeee);

    getchar();
    return 0;
}

我已经以strcpy的各种方式尝试过,但现在我认为main.c中的初始化调用可能存在问题。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您遇到的主要问题是您没有为struct本身分配空间,而是没有为keyvalue分配足够的内存。

此外始终检查您的分配是否成功。否则,您可能会冒未定义行为写入未分配给结构的内存的风险。

最后,当您分配内存时,您有责任跟踪它并在完成后释放它。以下是您的代码的简短示例:

#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)

答案 1 :(得分:1)

写作时

 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相同)

答案 2 :(得分:1)

除了 Cyber​​Spock 之外我还注意到了另一件事

configParam *parametersReaded[];

如果你在声明时没有初始化它们,你需要给出一些数组元素(这是一般的C概念)。