Reputation: 2294
I have been solving a problem of CyclicRotation. This is my code:
#include<stdio.h>
#include<stdlib.h>
struct Results{
int *A;
int N;
};
struct Results solution(int A[], int N, int K){
struct Results result;
int *tab, i=0, j=0;
tab = (int*) malloc(N*sizeof(int));
if(N==0){
result.A = A;
result.N = N;
return result;
}
if(K>N){
K = K % N;
}
if(K<N && N != 0){
for(i=N-K;i<N;i++){
tab[j] = A[i];
j = j + 1;
}
i = 0;
while(i<N-K){
tab[j] = A[i];
i++;
j++;
}
} else {
tab = A;
}
result.A = tab;
result.N = N;
return result;
}
int main()
{
int j[]={2,3,4,5,6,7,8};
int mylen;
int myk = 3;
mylen = sizeof(j)/sizeof(j[0]);
return 0;
}
I tried this in the code:
int main()
{
int j[]={2,3,4,5,6,7,8};
int mylen;
int myk = 3;
mylen = sizeof(j)/sizeof(j[0]);
printf("The result is %d",solution(j,mylen,myk).A);
return 0;
}
The expected result is 6782345, but the result in the console is different:
The result is -591373584
I'm not sure if the array printing is correct (given that is an array, perhaps I need a loop?). Please, could you give me a help? Thank you in advance.
Upvotes: 0
Views: 87
Reputation: 188
int main()
{
int j[]={2,3,4,5,6,7,8};
int mylen;
int myk = 3;
mylen = sizeof(j)/sizeof(j[0]);
struct Results results = solution(j, mylen, myk);
for(int i = 0; i < mylen; i++)
printf("%d\n", results.A[i]);
free(results.A);
return 0;
}
Upvotes: 1