1

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;
}
9
  • Are you aware that sizeof is not the same as len, right? Commented Oct 24, 2018 at 17:42
  • 2
    See stackoverflow.com/questions/1461432/what-is-array-decaying Commented Oct 24, 2018 at 17:43
  • @dbush I ask that you remove the duplicate status, since that link doesn't address my problem. It discusses using ` (sizeof(nlist)) / sizeof(nlist[0])` to determine the number of elements in an array. However my question is why does (sizeof(nlist)) / sizeof(nlist[0]) STOP working after the array has been passed to a function. Thanks! Commented Oct 24, 2018 at 20:13
  • 2
    See this answer on the linked thread Commented Oct 24, 2018 at 20:58
  • 2
    Detail: "why that stops working after the array has been passed to a function" --> In isItemInIntArray(int value, int arr[]), int arr[] is not an array, but a pointer. Thus sizeof(arr) is the size of a pointer. There are alternatives to sending the array size as a separate argument, yet they likely do not meet your coding goals. Commented Oct 27, 2018 at 22:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.