0

I'm trying to jump from an element to another element with a specified number for jumping and how many times it jumps, for example, k=4, and if it reaches the end it goes back from where it started. For example, as in the code, the array for a[Max] will be like {1,4,7,1}

#define Max 100
int main() {
   int i=0,n,k,counter,j=0;
   char v[Max]={1,2,3,4,5,6,7,8};
   int a[Max];
   k=4;
   counter=k+1;
   int size=strlen(v);
   while(counter!=0) {
       for(i=0;i<size;i=i+k-1){
           a[j]=(int)v[i];
           j++;
           counter--;
       }
   }
}

1 Answers1

0

You shouldn't be using a string or strlen() for this. Use an int array and you can get the size of your int array by using sizeof. Here, sizeof(v) will tell you the number of bytes allocated for your array, which in this case is 36 (Assuming ints are 4 bytes). Then you can divide by the number of bytes of an integer with sizeof(int) to get the number of elements in your array, 9.

You're segfaulting because you're writing outside the bounds of your array. You don't need that outer loop and should remove it entirely. To get the wrapping around of your array, use the modulus operation (%) with the size of your array. Understanding The Modulus Operator %

#include <stdio.h>

#define MAX 100
int main() {
    int i = 0, ii = 0, k = 4, counter = k - 1, j = 0;
    int v[]= {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int a[MAX];
    int size = sizeof(v) / sizeof(int);

    for (i=0; counter >= 0; i += k - 1) {
        a[ii++] = v[j];
        counter--;
        j = (j += 3) % size;
    }

    for (int i = 0; i < k; i++) {
        printf("%d\n", a[i]);
    }
}

Output:

1
4
7
1
codyne
  • 552
  • 1
  • 9