Sci-Walk
Sci-Walk

Reputation: 3

Count elements in array inside function

I know that similar question was asked but, I need some explanation: There is a code:

#include <stdio.h>
#include <stdlib.h>

int count_pieces(double *array){
    int i = 0;
    while(*(array + i)){  
        i++;
    }
    return i;
}
int main()
{   
    int i;
    int n=1005;
    double r[n];
    for(i=0;i<n;i++){
        *(r+i) = 100.0;
        printf("%f\n", *(r+i));
    }
    printf("\n----------------------\n");
    printf("N=%d",count_pieces(r)); 
    printf("\n----------------------\n");
    return 1;
}

count_pieces() was taken from know-all.net and was adapted for double. All works FINE. BUT! - when I comment line: printf("%f\n", *(r+i)); It becomes work incomprehensible! Why? What's happening?

Upvotes: 0

Views: 65

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

You can't count items in a double array, that technique is used for strings, because in c strings have a special last value '\0' which is basically 0, hence it can be used as a truth value in a loop to help count characters or find the end of the string for any other purpose.

Specially in your case, all the elements are 100.0, so why are you expecting while (*(array + i)) to even start looping?

Also, you need to be clear about the syntax *(array + i) which is the same as array[i] and it's obvious which of the two is better.

In c you need to keep track about the number of elements of an array, if you want to "though I don't like that" you can use a struct

struct DoubleArray  
{
    double *data;
    size_t  size;
};

and then you could use functions to initialize, deinitialize, set/get values etc., for example

struct DoubleArray *new_double_array(size_t size)
{
    struct DoubleArray *array;
    array = malloc(sizeof(*array));
    if (array == NULL)
        return NULL;
    array->data = malloc(size * sizeof(double));
    if (array->data == NULL)
    {
        free(array);
        return NULL;
    }
    array->size = size;

    return array;
}

And then I'd recommend to make this struct opaque, i.e. to hide it's fields from the struct users, so that you can prevent misusing the fields.

Upvotes: 3

Natasha Dutta
Natasha Dutta

Reputation: 3272

As I can see, in your code,

while(*(array + i)){ 

does not include any boundary check on the index i. So, it will create memory overrun and hence you'll face undefined behaviour.

It does not have any effect for commenting out printf("%f\n", *(r+i));.

Also, there is a fundamental problem in your count_pieces() function. Without checking the input parameter array against NULL, you started to deference it. It can cause you serious trouble if the function is called with a NULL argument. You should put a check first.

Upvotes: 1

Related Questions