Похожие чаты

Guys Im passing an array to a function The function defination is

like this:
int my_funcie(int *arr);

It takes an array of integers, and let's say it prints the array's elements

The problem is I want to use a for loop to print elements, and I don't want to hardcode the condition
For example

for(int index = 0; index < array_length; index++)

here, the array_size is the problem
According to this StackOverflow answer

It should work using this piece of code:
int array_length = sizeof(arr) / sizeof(arr[0])

I put this inside my my_funcie function, but it doesn't give me the proper result
For example It's saying the array with 5 integer elemnts (sizeof(arr)) is 8 and the sizeof(arr[0]) is 4
It does 8/4 and gets 2 as the array_length

What am I doing wrong?
The same method works pretty well where I defined the array itself

I'm using C and gcc 9.2.0 btw

3 ответов

11 просмотров

It doesn't work this way if you're getting the array as a function parameter. Go through the ss posted by John it'll explain this in detail. Instead of array you can use vectors. Personally I prefer vectors over arrays plus vectors have their own size() function which will give you an exact count of the number of elements present inside it.

rewrite the function signature as int my_funcie(size_t size, int arr[size])

Jens Gustedt's Modern C has multiple paragraphs about the difference between arrays and pointers. you should read them. the book is linked in the pinned message.

Похожие вопросы

Обсуждают сегодня

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?
Rꙮman Yankꙮvsky
29
А вообще, что может смущать в самой Julia - бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как "хаки" и произвол. Короче говоря, с...
Viktor G.
2
@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Гайс, вопрос для разносторонее развитых: читаю стрим с юарта, нада выделять с него фреймы с определенной структурой, если ли чо готовое, или долбаться с ринг буффером? нада у...
Vitaly
9
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Карта сайта