tags:

views:

174

answers:

3

Hi, Basically in the code below, my final array does not seem to have the contents from function1(). Any ideas on why I can't get this to work ? Thanks.

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

  unsigned char *function1() 
 {
  unsigned char array2[] = { 0x4a,0xb2 };
  return (array2 );

  }

   main()

     {
unsigned char temp[] = { 0xaa, 0x0b, 0x03,0x04,0x05,0x06,0x07,0x08,0x09 };
unsigned char x[2];
unsigned char *packet;
int pkt_len;
pkt_len = sizeof(temp) + sizeof(x);
packet = (unsigned char*) malloc ( pkt_len +1);

memset( packet, 0x00, pkt_len +1);
unsigned char *pointer1 = malloc ( sizeof(temp) + 1);

memset( pointer1, 0x00, sizeof(temp) +1);
memcpy (pointer1, temp, sizeof(temp) );

memcpy (packet, pointer1, sizeof(temp) );
printf("\nPacket before copy is 0x%x\n", packet[8]);

    unsigned char *array2 = malloc ( sizeof (x) + 1)  ;
    array2 = (char *)function1();
printf("\nArray2 is 0x%x\n", array2[0]);
    memcpy (packet + sizeof(temp), array2, sizeof(x) );
printf("After copy, Packet contents are 0x%x\n", packet[9]);
  }
A: 

It's not really clear precisely what you're trying to do, but I think this is what you're after. I've commented it to show what it's doing.

void function1(char *dest, size_t len);

int main() 
{
  /* Allocate an array 'temp' */
  char temp[] = { 'a', 's', 'd', 'f', 'g', 'h' };

  /* Allocate an array 'array1', the same size as 'temp' */
  char array1[sizeof temp];

  /* Copy the contents of 'temp' into 'array1' */
  memcpy(array1, temp, sizeof temp);

  /* Call a function to copy new contents into 'array1' */
  function1(array1, sizeof array1);

  return 0;
}

void function1(char *dest, size_t len)
{
  char temp2[] = { 1, 2, 3, 4, 5 };

  /* Determine how much to copy - the _minimum_ of 'len' and 'sizeof temp2' */
  if (len > sizeof temp2)
  {
      len = sizeof temp2;
  }

  /* Copy contents of 'temp2' into 'dest' */
  memcpy(dest, temp2, len);
}
caf
Thanks caf. The only diff. is I want to merge the contents of the array in the main loop and not in the function1 loop. ( Look at the changed code I have uploaded). Thanks for your time.
A: 

I cant seem to understand your code. The problem is simple but the code wont work. Next is this piece of code memcpy ( pointer1 + sizeof(temp), pointer3, sizeof ( the temp array)

I guess you want the final array to contain { a,b,c,d,e,1,2,3,4,5}. Well i would advise you to check pointers and arrays from K&R and then attempt this problem again.

Praveen S
+2  A: 
Andrew-Dufresne
Andrew, thanks for your excellent reply. Cleared up so many things.So I have added some new code here? Could you advise me on why packet[9] does not display the right contents even though array2[0] does have the right content ?