EmbeddedCrazy
EmbeddedCrazy

Reputation: 31

Unable to pass and retrieve array element?

Hi friends I am trying to assigned elements from arr2[] to a pointer p_arr and then trying to print from p_arr...

I think something is messing up, not getting expected values...

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

#define MAX_ONE   9
#define MAX_TWO   9


int arr1[] = {10,20,30,40,50,67,23,47,79};
int arr2[] = {5,15,25,35,45,34,45,67,89};

int *main_arr[] = {arr1,arr2};

int main()
{
    int i;
    int *p_arr2;

p_arr2 = (int *)malloc(sizeof(int)*2); 

    for(i=0;i<MAX_ONE;i++)
    {
        *p_arr2++ = arr2[i];
        arr2[i] = arr1[i];
    }

    for(i=0;i<MAX_TWO;i++)
    {
        printf("%d\n",*(p_arr2));
        p_arr2++;
        //printf("%d\t",arr2[i]);
    }

    system("PAUSE");   

    return 0;
}

Upvotes: 0

Views: 77

Answers (3)

999k
999k

Reputation: 6565

Try this. Also always try to free dynamically allocated memory

     p_arr2 = malloc(sizeof(int)*MAX_ONE); 

      for(i=0;i<MAX_ONE;i++)
      {
           p_arr2[i] = arr2[i];
           arr2[i] = arr1[i];

      }

     for(i=0;i<MAX_TWO;i++)
     {
            printf("%d\n",*(p_arr2 + i));;
            //printf("%d\t",arr2[i]);
     }
     free (p_arr2);

Upvotes: 0

gcbenison
gcbenison

Reputation: 11963

In addition to the allocation issues mentioned, before you start the print loop, you don't reset p_arr2 to point at the start of the array. So you're printing from uninitialized memory.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206518

p_arr2 = (int *)malloc(sizeof(int)*2); 

You allocated only enough memory for 2 integers and you are trying to store MAX_ONE in this array. This results in writing beyond the allocated memory block and an Undefined behavior.

You need to allocated enough memory to store MAX_ONE elements.

p_arr2 = malloc(sizeof(int)*MAX_ONE); 
                           ^^^^^^^^^

Also, you do not need to cast the return type of malloc in C.

Upvotes: 2

Related Questions