0

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;
}
1
  • p_arr2 = (int *)malloc(sizeof(int)*MAX_ONE); is correct for creating an array of size MAX_ONE. Also after first loop p_arr2 points to last elemnt. Commented Mar 4, 2013 at 5:56

3 Answers 3

2
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

1 Comment

Thanks buddy...I appreciate your efforts!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.