EDIT: I believe this question is different from How do I determine the size of my array in C?, because that link discusses how to use sizeof(nlist)) / sizeof(nlist[0])
to determine the number of items in an array.
My question is asking why that stops working after the array has been passed to a function.
===
I'm new to ansi C, coming from Python.
I have a function that parses an int
array. The iteration through the array is dependent on sizeof(nlist)) / sizeof(nlist[0])
to determine the size of the array.
However, while this works in main()
, it fails when the array is passed to a function.
In main file
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "arrayTools.h"
int main() {
// Fill with data for testing
int nlist[500];
for (int i=1; i<501; i++ ) {
nlist[i] = i;
}
// This successfully iterates through all 500 items
for( size_t i = 1; i <= (sizeof(nlist)) / sizeof(nlist[0]); i++)
{
printf(isItemInIntArray(i, nlist) ? "true\n" : "false\n");
}
arrayTools.h
#include <stdbool.h>
#include <stdlib.h>
bool isItemInIntArray(int value, int arr[]){
// This only iterates twice (i = 1, then i = 2) and then ends
for( size_t i = 1; i <= (sizeof(arr)) / sizeof(arr[0]); i++) {
if (value == arr[i]) { return true; }
}
return false;
}