Harrison
Harrison

Reputation: 23

How to get values from an array when you pass in a pointer to a function?

I am trying to make a function that implements comb sort but I am having trouble with my code actually reading the array that I am trying to input.

void comb_sort(int* numbers, int size)
{
int gap = size;
float shrink = 1.3;
int sorted = 0;

do
{

    gap = gap/shrink;
    if (gap > 1)
        sorted = 0;
    else
    {
        gap = 1;
        sorted = 1;
    }

    int i = 0;
    do
    {
        if (numbers+i > numbers+(i+gap))
        {
            swap(numbers+i,numbers+(i+gap));
            sorted = 0;
        }
        i++;
    }while(i+gap < size);


} while (sorted == 0);
}

the numbers parameter is an array in my main function but since I want to change the values I'm passing in the pointer. But, the if statement that contains it doesn't actually seem to have the values of the array that I pass in to it. When testing it with gdb it just had 1 stored inside of it, even though I verified that the array had all the values from the text file inside of it. Is there notation I am getting wrong?

EDIT* here's the code for my main function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sorting.h"

int main(int argc, char* argv[]){

FILE *list;
list = fopen(argv[1],"r");
int data_size = 0;
int num;

while (fscanf(list,"%d ",&num) == 1){
    data_size++;
}
fseek(list,0,SEEK_SET);
int num_array[data_size];
int j;
for (j=0;j<data_size;j++){
   fscanf(list,"%d ",num_array+j);
}

if (strcmp("comb", argv[2]) == 0)
    comb_sort(num_array,data_size);

Upvotes: 0

Views: 44

Answers (1)

user2736738
user2736738

Reputation: 30926

numbers+i is an address not the value. It should be *(numbers+i) or even clearly numbers[i].

In the if statement condition you are comparing two addresses not value which you wanted.

Upvotes: 2

Related Questions