简体   繁体   中英

Print elements from an array member of a structure in C

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM