将值填充到指针数组

时间:2011-07-27 20:59:49

标签: c arrays pointers

最近我已经完成了理解和学习C的任务。现在我正在学习结构和指针数组。我有个问题。我想用值填充指针数组。以下是我的代码:

           struct profile_t 
          {
           unsigned char length;
           unsigned char type;
           unsigned char *data;
          };

          typedef struct profile_datagram_t
         {
          unsigned char src[4];
          unsigned char dst[4];
          unsigned char ver;
          unsigned char n;
          struct profile_t profiles[MAXPROFILES];       
         } header;

          header outObj;

         int j =0;
         int i =0;

      outObj.profiles[j].data = malloc(10);

      for(i=0;i<10;i++)
          {
         if (j=0)
             {
           outObj.profiles[j][i] = 1 2 3 4 5 6 7 8 9 10;
         }
         else 
             {
        j=1;
         }
      }

      for(i=0;i<10;i++)
          {
        if (j=1)
            {
           outObj.profiles[j][i] = 1 2 3 4 5 6 7 8 9 10;
        }
      }

上述方法是否可行,或者我完全偏离了轨道。 MAXPROFILES为2(仅表示0和1)。

3 个答案:

答案 0 :(得分:1)

你不能像这样分配

outObj.profiles[j][i] = 1 2 3 4 5 6 7 8 9 10;

outObj.profiles[j]是profile_t实例。 outObj.profiles[j].data是char *。 我想你想要将整数分配给数据。 首先,你应该为两个j值分配内存。

outObj.profiles[0].data = malloc(10);
outObj.profiles[1].data = malloc(10);

我建议你用类似这样的循环替换你的代码

for(i=0;i<10;i++) {
    outObj.profiles[0].data[i] = i+1;
    outObj.profiles[1].data[i] = i+1;
}

结果相同,但阅读和理解起来要清晰得多。

答案 1 :(得分:0)

或简而言之:

#define DATALENGTH 10

uint actProfile = 0;
uint actData = 0;



for( actProfile = 0; actProfile < MAXPROFILES; ++actProfile )
{
    outObj.profiles[actProfile].data = malloc(DATALENGTH);

    //skip check if malloc was successfull...

    for ( actData = 0; actData < DATALENGTH; ++actData )
    {
      outObj.profiles[actProfile].data[actData] = actData +1;
    }
}

答案 2 :(得分:0)

您没有为outObj.profiles[1].data分配空间。

数字序列(1 2 ... 10)是语法错误。您可能想要使用循环变量

for (i = 0; i < 10; i++) {
    outObj.profiles[0][i] = i + 1;
}
相关问题