开发者

Populating values to a pointer array

Off lately I have taken up the task to understand and learn C. Right now I was learning about structures and pointer arrays. I have a problem. I want to populate a pointer array with values. Below is my code:

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

  开发者_StackOverflow中文版    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;
        }
      }

Is the above approach the way to go or am I completely offtrack. MAXPROFILES is 2 (which means only 0 and 1).


You cannot assign like this

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

outObj.profiles[j] is profile_t instance. outObj.profiles[j].data is char*. I suppose that you want to assign that integers to data. First of all you should allocate memory for both j values.

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

I suggest you to replace your code with loops with something like this

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

The result is same but it is much cleaner to read and understand.


Or in short:

#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;
    }
}


You don't allocate space for outObj.profiles[1].data.

The sequence of numbers (1 2 ... 10) is a syntax error. You may want to use the loop variable

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜