1

I'm trying to create a code in using C that creates an array, swaps all the numbers in the array, and tests which sort method is faster, but for some reason it stops swapping after exactly 32768 numbers, I'm pretty new to coding and I don't know what i'm doing wrong

void swap(int *a, int *b){
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}
for(k=0;k<nswap;k++){
        r1=rand()%max;
        r2=rand()%max;
        swap(&vet[r1],&vet[r2]);
    }

This is just a part of the code, every variable has been declared correctly.

Edit: The array "vet" is initialized as vet[max] where max is a "#define max 35000"

by "stop" i mean that r1 and r2 don't swap numbers that are higher then 32768.

"k" is just a variable i use in loops. "k" does get higher then 2^15 but r1 and r2 don't

here's a reproducible example:

#include <stdio.h>
#include <stdlib.h>
#define max 35000
#define nswap 35000
void swap(int *a, int *b){
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}

int main(int argc, char *argv[]) {
    srand(time(NULL));
    int vet[max];
    int vettemp[max];
    int k, r1, r2, temp;

for(k=0;k<max;k++){
        vet[k]=k+1;
    }

    for(k=0;k<nswap;k++){
        r1=rand()%max;
        r2=rand()%max;
        swap(&vet[r1],&vet[r2]);
    }
for(k=0;k<max;k++){
        printf("%d ", vet[k]);
    }
return 0;

This is where my problem comes

I've tried to eliminate some useless declaration but it didn't work

  • 1
    Maybe hit a storage or memory limit? Why not stop at a given point, refresh or clear then continue from that point. – Solar Mike Jan 23 '23 at 07:59
  • 1
    What are `k` and `nswap`? Are there any 16 bit signed integers involved? – Gerhardh Jan 23 '23 at 08:02
  • 1
    How do you detect that swapping ends? – Gerhardh Jan 23 '23 at 08:02
  • What is `vet` and what is `max`? – pmacfarlane Jan 23 '23 at 08:02
  • 7
    Check your manual... On some systems, RAND_MAX is 32767... – Fe2O3 Jan 23 '23 at 08:03
  • Is the array `vet` initialised? If not, accessing its members invokes [undefined behaviour](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). – pmacfarlane Jan 23 '23 at 08:06
  • 2
    Please provide a [mre] and report the size of `int` (the datatype of `temp`) in your environment. – Yunnosch Jan 23 '23 at 08:07
  • 2
    Do you mean k < 2^15 irregardless the value of nswap? Or do you mean that r1 and r2 never get bigger than 2^15? "stop" usually means something very specific, i.e. program termination. – Allan Wind Jan 23 '23 at 08:07
  • `rand()` will return a value between 0 and [`RAND_MAX`](https://en.cppreference.com/w/c/numeric/random/RAND_MAX). `RAND_MAX` is implementation-defined and guaranteed to be at least 32767. You may try to print the value on your system. – nielsen Jan 23 '23 at 10:26

0 Answers0