Integer array length


 
Thread Tools Search this Thread
Top Forums Programming Integer array length
# 1  
Old 09-08-2013
Integer array length

Hello;
When I wrote a function to print out an array,
Code:
void p_array(int arr[])
 {
   int i;
    int size = sizeof(arr) / sizeof(int);
 //    int size = sizeof (arr) / sizeof (arr[0]);
     for (i = 0; i < size; i++)
         printf("%d ", arr[i]);
     printf("\n");
 }

I could only print out the first two elements,( sometimes 8 out of 10 elements). What did I miss?
The problem seems to be the part
Code:
size = sizeof arr/sizeof(int);
size = sizeof arr /sizeof arr[0];

My understanding is (copied from stackoverflow):
sizeof returns the size in memory of the passed element. By dividing the size of an array by a single element size, you get the elements count. On the other hand, when counting elements in an array: sizeof(a) / sizeof(a[0]) will still work as well.
But my code does not! I saw this type online quite lot, but mine just does not work (Ubuntu 12.10, 64_bits kernel). Could anyone explain what is wrong with my code? Thanks a lot!
# 2  
Old 09-08-2013
Your array is passed as a pointer. There's no way for your function to know the size of the array, unless you pass that too.

i.e.
Code:
void p_array(int arr[], int size) {
 ...
}

A 64-bit pointer (8 bytes) divided by an integer of 4 bytes = 2, which is why you're seeing only two elements.
This User Gave Thanks to Scott For This Post:
# 3  
Old 09-08-2013
Code

i'll try your code on my machine once i'll get to home but i would rather like to do this by
Code:
void p_array(int arr[])
 {
       int *a = arr;
 //    int size = sizeof (arr) / sizeof (arr[0]);
     while(a!=NULL)
        { printf("%d ", *a);a++}

     printf("\n");
 }


Last edited by Scott; 09-08-2013 at 10:52 AM.. Reason: Code tags
# 4  
Old 09-08-2013
Quote:
Originally Posted by kg_gaurav
i'll try your code on my machine once i'll get to home but i would rather like to do this by

void p_array(int arr[])
{
int *a = arr;
// int size = sizeof (arr) / sizeof (arr[0]);
while(a!=NULL)
{ printf("%d ", *a);a++}

printf("\n");
}
You can't.
# 5  
Old 09-08-2013
Thanks everybody!
Scott, what I want is to let my function by itself get the size of the array, especially when the array size is unknown.
Your explanation about "2" is what I thought, but how come sometime it print 8 elements of the array?
I feel it is related to array and pointer/address, but I could not figure it out myself, especially when google gives many discussions, for example, this one. but I am still unclear the problem with my code. Thanks a lot again!
# 6  
Old 09-08-2013
Quote:
Originally Posted by yifangt
Your explanation about "2" is what I thought, but how come sometime it print 8 elements of the array?
Show us the code that prints 8 elements. An entire program, not just the printing function. If it is an extremely long program, eliminate all non-essentials and construct a minimal case that still prints out 8 elements. Perhaps then, we can provide accurate feedback.

Given what you've shown us, I believe Scott's explanation is as good as it gets. For more info regarding his point, refer to the comp.lang.c FAQ - Question 6.4.

Regards,
Alister
# 7  
Old 09-08-2013
Here is my code, which is for quick sort I am trying to understand each step of the algorithm.
Code:
1 #include<stdio.h>

3 void qsort(int[], int, int);
4 void p_array(int[]);

6 int main()
{
8    int i;
9   int array[] = { 55, 66, 32, 12, 9, 73, 2, 4, 37, 36 };
10    int len = sizeof(array) / sizeof(int);
11    for (i = 0; i < len; i++)
12    printf("%d ", array[i]);
    printf("\n");
14    p_array(array);

    qsort(array, 0, len - 1);
17    for (i = 0; i < len; i++)
18    printf("%d ", array[i]);
    printf("\n");
    return 0;

}

 23  void qsort(int a[], int left, int right)
{
    int pivot, l, r, temp;

    l = left;
    r = right;
    pivot = a[(left + right) / 2];

    while (l < r) {
    while (a[l] < pivot) {
        ++l;
34          p_array(a);
    }
    while (a[r] > pivot) {
        --r;
38          p_array(a);
    }
    if (l >= r)
        break;
    temp = a[l];
    a[l] = a[r];
    a[r] = temp;
    ++l;
    --r;
47     p_array(a);
    }
    if (l == r) {
    l++;
51      p_array(a);
   }
    if (left < r) {
    qsort(a, left, l - 1);
55      p_array(a);
    }
    if (l < right) {
    qsort(a, r + 1, right);
59      p_array(a);
    }
60    p_array(a);
}

63 void p_array(int arr[])
{
    int i;
66    int size = sizeof(arr) / sizeof(int);
//    int size = sizeof (arr) / sizeof (arr[0]);
    for (i = 0; i < size; i++)
    printf("%d ", arr[i]);
    printf("\n");
}

I labeled the p_array call for convenience when you point out the problem. I could not understand in the main function line 10, which works fine, but not
line 66.
Output:
Code:
55 66 32 12 9 73 2 4 37 36 // this from line 10 ~ 12, which is correct
55 66 
2 4 
...
2 4 
2 4 9 12 32 36 37 55 66 73 // this from line 17 ~ 18 which is also correct

Why?
By the way, this is NOT an assignment from school, but my self-study. Appreciate any input. Thanks a lot!

Last edited by yifangt; 09-09-2013 at 01:49 AM.. Reason: improve the question
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Array length: ls and sort

Hi there, I'm listing files and sorting them. When I try to get length of array variable in which these files are stored I get 1 as value. That's weird. files_info="$(find $input_dir -name "*_CHR$i.info" | sort )" printf ${#files_info}"\n" #print length #--loop through... (6 Replies)
Discussion started by: genome
6 Replies

2. Shell Programming and Scripting

How to find length of multidimension array ???

Does anyone know how to find length of multi dimension array of following type A Afor simple array I is to do for (i in A)n++ to find length of array but if it is multi dimension how to find the length ? (2 Replies)
Discussion started by: nex_asp
2 Replies

3. Shell Programming and Scripting

Array Length Reports as Having Length when it is Empty?

Hello All, I have this script that does stuff like "starting, stopping & restarting" a Daemon Process running on my machine... My main question is why in part of my code (which you will see below) does the Array Length (i.e. ${#PIDS} ) return "1" when I know the Array is empty..? Here is... (17 Replies)
Discussion started by: mrm5102
17 Replies

4. Shell Programming and Scripting

Longest length of string in array

I would be grateful if someone could help me. I am trying to write a .sh script in UNIX. I have the following code; User=john User=james User=ian User=martin for x in ${User} do print ${#x} done This produces the following output; 4 5 3 6 (12 Replies)
Discussion started by: mmab
12 Replies

5. Shell Programming and Scripting

MAWK does not support length(array)?

As Brendan O'Conner writes in this blog, mawk is near 8 times faster than gawk, so I am going to give mawk a go, but I got errors when trying to print the length of an array in mawk using length() function, is it not supported in mawk? or there's another way to get the length of an array in mawk? ... (3 Replies)
Discussion started by: kevintse
3 Replies

6. Shell Programming and Scripting

Floating point to integer in variable length lines

Hi ! I'm looking for a way to transform certain floating point numbers in a one-line, variable length file to integers. I can do this in a crude way with sed : sed -e 's/0\.\(\):/\1:/g' -e 's/0\.0\(\):/\1:/g' -e 's/1\.000:/100:/g' myfile ... but this doesn't handle the rounding correctly. ... (3 Replies)
Discussion started by: jossojjos
3 Replies

7. Shell Programming and Scripting

Variable Sized Array Length Question

I need to implement the following logic and need some expert help from UNIX community. These are the steps in my Shell script. 1. Analyze a file. 2. Extract all the ID's in that file. 3. Use the ID's from #2 to run another filter on the file. I've implemented # 1 and 2 using... (3 Replies)
Discussion started by: katwala
3 Replies

8. UNIX for Advanced & Expert Users

converting openssl hex dump or PEM format to integer array

Hello. I'm working on a project that involves creating public/private keys server-side using openssl and using the public key in a Javascript application to encrypt sensitive data in form fields before transmission to the server. Using an SSL https server connection was not an option in this... (1 Reply)
Discussion started by: jhopper
1 Replies

9. Shell Programming and Scripting

Array length in PERL

Hi experts, How to get the length of an Array in PERL. for eg., @Var having 5 elements. regards Anent (5 Replies)
Discussion started by: anent
5 Replies

10. Programming

Function to return an array of integer

Hi all, I am trying to create a function that return an array of integer based on the char parameter pass into the function. I.e. func_a(char * str) { example str is equal to "1,2,3,4" return an array of integers of 1,2,3,4 } Please advise regards dwgi32 (2 Replies)
Discussion started by: dwgi32
2 Replies
Login or Register to Ask a Question