main function is not printing same o/p as structure function Why?
or
memcpy is not copying whole array
please help.
expected o/p
7 4 5 6 2
7 4 5 6 2
but
getting o/p
7 4 5 6 2
7 4 garbage garbage garbage
thanks in advance.
#include <stdio.h>
#include <string.h>
struct Result {
int output[100];
};
struct Result my(int length, int path, int input[]){
int temp=input[path-1];
for(int i=path-1; i>0; --i){
input[i]=input[i-1];
}
input[0]=temp;
for (int i = 0; i <= length; i++) {
printf(" %d",input[i]);
}
struct Result result;
memcpy (result.output, input, sizeof(strlen(input)));
return result;
}
int main(void){
int a[]={4,5,6,7,2};
struct Result res = my(4,4,a);
printf("\n");
for (int i = 0; i <= 4; i++) {
printf(" %d",res.output[i]);
}
return 0;
}
Two problems.
strlen
for int
array.memcpy
needs number of bytes to be copied.Hence change
memcpy (result.output, input, sizeof(strlen(input)));
to
memcpy (result.output, input, sizeof(input[0])*(length+1)); //length+1 since your passing array length-1
Note:
sizeof(input)
issizeof(pointer)
when array is passed as parameter to function.