Pointer question

A

amjadcsu

Hello.
I am trying to learn concept of pointers in C

I wrote a simple int copy program which basically copies the two int
arrays

char *mystrcpy( int *source, int *dest, int no)
{
printf("the first element of char is %d \n", *source);
int i;

for (i=0;i<4;i++)
{
*dest++ =*source++;
}

return dest;
}



int a[5]={2,3,4,5};
int i,j;
//char *ptrA;
//char *ptrB;
int b[5];
ptrA=a;
ptrB=b;
ptrB=mystrcpy (ptrA ,ptrB,3);
for (i=0;i<4;i++)
{
printf("the b array is %d \n",b);
}

So i would expect the output of this program to be
the b array is 2
the b array is 3
the b array is 4
the b array is 5
but i get the following output
the b array is 134518416
the b array is 3
the b array is 4
the b array is 5

Can someone tell me why the first element is messed up

thanks
 
B

Ben Bacarisse

Hello.
I am trying to learn concept of pointers in C

I wrote a simple int copy program which basically copies the two int
arrays

Better to post a program. These fragments just give an idea of what
is wrong.
char *mystrcpy( int *source, int *dest, int no)
^^^^
You probably mean int. The name reveals that this function once did
something else.
{
printf("the first element of char is %d \n", *source);
int i;

for (i=0;i<4;i++)
{
*dest++ =*source++;
}

return dest;

Your compiler whoudl have something to say about returning an int *
when the function is declared to return a char *. If you did not get
a message about this, you need to ask for more help from you compiler
(turn the error level as high as possible).

Note, that dest (the value you return) now points four elements furth
along the array than the parameter that was passed in.
}



int a[5]={2,3,4,5};
int i,j;
//char *ptrA;
//char *ptrB;
int b[5];
ptrA=a;
ptrB=b;
ptrB=mystrcpy (ptrA ,ptrB,3);

Your compiler should have told you about this too. There are two
errors here. You can't assign to an array (b) and the return type of
mystrcpy is wrong. Don't ignore you compiler's help.
for (i=0;i<4;i++)
{
printf("the b array is %d \n",b);
}

So i would expect the output of this program to be
the b array is 2
the b array is 3
the b array is 4
the b array is 5
but i get the following output
the b array is 134518416
the b array is 3
the b array is 4
the b array is 5

Can someone tell me why the first element is messed up


It is not. I can't think how you got this code though a compiler, but
whatever you did, the return from your function is not a pointer to
the copied data. It points past it (see above). To get a more
detailed answer, you'd have to post a program that compiles.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top