0
int main()
{
 unsigned char a[3];
 unsigned char (*p)[3]=NULL;
 unsigned char *q=NULL;
 int i = 0;
 a[0]=0;
 a[1]=1;
 a[2]=2;
 p=&a;
 for(i=0;i<3;i++){
   if((*p)[3] == a[3]){
     printf("*p[%d]:%d a[%d]:%d",i,(*p)[3],i,a[3]);
   }
 }
}

o/p:
*p[0]:0 a[0]:0*p[1]:0 a[1]:0*p[2]:0 a[2]:0
Exited: ExitFailure 14

I want to copy an array of size 3 to a pointer and to do a comparision. I have written a sample program. But i'm getting an error value. I ran this using an online c compiler . (codepad.org) Please help me in identifying my mistakes.

1
  • You seem to forget that that arrays start their indexing at zero, and the highest index is the size minus one. Commented Jul 20, 2012 at 7:04

2 Answers 2

4

Your variable p is an array, not a pointer. You can't re-assign an array to point somewhere else, so the line

p = &a;

is not valid.

Also, C indexes from 0 as you seem to know, so comparisons using index [3] for arrays of size 3 are not valid.

Further, in your comparison loop you're not actually using i to index, but instead always comparing using the invalid constant index [3].

It's not very clear from your code (q is not used, for instance), but it sounds as if you want to do something like:

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

unsigned char a[3];
unsigned char *p;

p = malloc(sizeof a);
if(p != NULL) /* If allocation succeeded, p is valid. */
{
  int i;

  memcpy(p, a, sizeof a);
  for(i = 0; i < sizeof a; ++i)
  {
    if(p[i] == a[i])
      printf("p[%d]:%d a[%d]:%d\n", i, p[i], i, a[i]);
  }
  free(p);
}

Of course, this will always print all the numbers, since memcpy() will never fail to copy the memory. :)

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

Comments

1

Here You have declared the return type of main function as int, but you are not returning anything from it. So return any integer value (like 1) or make the main function's return type void.

Comments

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.