Sandeep Ghemire Sandeep Ghemire -4 years ago 84
C Question

Copying a subarray into another array

#include<stdio.h>
int copy(char d[],char e[],int n);
int main(void)
{

char a[20]="Nice to meet you";
char b[10];
copy(a+5,b,4);
return 0;
}

int copy(char d[],char e[],int n)
{
for(int i=0;i<n;i++)
{
e[i]=d[i];
}
printf("%s\n",e);
return 0;
}


Here
d
points to
a+5
and
e
points to
b
. Here I understood that the output would be "
to m
".
My question is: in
copy
function if I initialize
i
to run from
1
to
n-1
instead of
0
to
n-1
, why is it not giving the desired output?
I expected the new output to be "
o m
".

Answer Source

If you loop with i in copy from 1 to n - 1, then after calling copy(a + 5, b, 4) in main, b[0] will still be uninitialised, so accessing it is undefined behaviour (you aren't making sure the string in b ends in a '\0', either). Even if it weren't, it would still be there; for it to print "o m" you would have to start reading from b + 1, or do the assignment in copy like e[i - 1] = d[i] (and make sure to nul-terminate it if you're going to treat it as a string after, or treating it as a nul-terminated string will have it read past the end into uninitialised territory and similarly invoke undefined behaviour).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download