为char数组分配动态内存

时间:2014-05-07 05:35:13

标签: c malloc structure

我必须将存储在struct中的一些值打印到单个char数组中,我没有得到一个为变量数组值分配内存的简单方法。

下面我需要做的代码snnipet

 struct types {

char *name;
char *address;
char * descrption;
};

int main ()
{

  int numberofUser = 10;

  struct types allUsers[numberofUser];

  //Assume here I filled all the user details by allocation memory.

  // now I need to print these values in the formated string like below


 char* outputString;

 int i ;
 for(i =0 ; i<numberofUser;i++)
 {
 sprintf(outputString,"<start>name=%s,add=%s,des=%s",allUsers[i].name,allUsers[i].address,allUsers[i].descrption);
 }
}

如何为可以容纳所有结构值的输出字符串分配内存

4 个答案:

答案 0 :(得分:1)

  1. 定义格式字符串并将其存储在自己的变量中。

    char const* formatString = "<start>name=%s,add=%s,des=%s";
    
  2. 获取格式字符串的长度。

    size_t formatStringLen = strlen(formatString);
    
  3. 获取结构成员的长度。

    size_t nameLen = strlen(allUser[i].name);
    size_t addLen = strlen(allUser[i].address);
    size_t desLen = strlen(allUser[i].description);
    
  4. 分配足够的内存来保存格式字符串以及结构的成员。

    // This will be more than the exact space you need but certainly
    // not less than what you need and not too much more than what you
    // need.
    size_t totalLen = formatStringLen + nameLen + addLen + desLen;
    outputString = malloc(totalLen);
    
  5. 使用sprintf

     sprintf(outputString, formatString,
             allUsers[i].name, allUsers[i].address, allUsers[i].descrption);
    

答案 1 :(得分:0)

您需要计算所涉及的字符串长度并为其分配大量内存。像

这样的东西
int len = 0;

len = strlen(allUsers[i].name) 
      + strlen(allUsers[i].address) 
      + strlen(allUsers[i].descrption);
len += strlen("<start>name=") 
     + strlen(",add=") 
     + strlen(",des=");
len ++ // for '\0'

outputString = malloc(sizeof(char) * len);

注意:这是allUsers中的1条记录,因为字符串可能会在其他元素中发生变化。

您应检查有效指针,并在使用后释放内存。

答案 2 :(得分:0)

如果您的编译器支持C99,那么它应包含函数snprintf。要分配和设置字符串,可以使用以下代码:

char *outputString;
int  len;
outputString = NULL;
len = 0;
for(;;) {
    // this loop is executed only two times
    len = 1 + snprintf(outputString, len, "<start>name=%s,add=%s,des=%s",allUsers[i].name,allUsers[i].address,allUsers[i].descrption);
    if (outputString != NULL) break;                  // success
    outputString = realloc(outputString, len);
    if (outputString == NULL) break;                  // fail
}

答案 3 :(得分:0)

结构的成员是字符的指针,即char *类型的指针,但是你需要一个字符数组来存储字符串。数组的大小必须大于字符串可以容纳的终止空字节的最大长度,该空字节标记字符串的结尾。我建议进行以下更改 -

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

#define NAMELEN 20+1  // max length of name + 1
#define ADDRLEN 40+1  // max length of address + 1
#define DESCLEN 80+1  // max length of description + 1

struct types {
    char name[NAMELEN];
    char address[ADDRLEN];
    char descrption[DESCLEN];
};

int main(void) {
    int numberofUser = 10;
    struct types allUsers[numberofUser];

    // assign values to array elements        

    // format string for sprintf
    const char *fstr = "<start>name=%s,add=%s,des=%s";

    // strlen doesn't count the null byte. macros include null byte
    // so get space for 2 extra null bytes which is not needed.
    int outlen = strlen(fstr) + NAMELEN + ADDRLEN + DESCLEN - 2;

    // variable-length to store the output string
    char outputString[outlen];

    for(int i = 0; i < numberofUser; i++) {
        sprintf(outputString, "<start>name=%s,add=%s,des=%s",
                allUsers[i].name,
                allUsers[i].address,
                allUsers[i].descrption);

        // print the string
        printf("%s\n", outputString); 
    }
    return 0;
}