Thread: I have trouble understanding this code

  1. #1
    Registered User
    Join Date
    Sep 2015
    Posts
    3

    I have trouble understanding this code

    This might be a stupid question, but I thought arrays start from index 0. So when we say print_array(data, 3)why is it only printing 10 20 30? why 40 is not included? isnt 40 index 3?!
    I will appreciate if anyone can clarify this for me.

    Code:
    #include <stdio.h>
    void print_array(int *p, int size) {  /* int *p could have been written as int p[] */   int idx = 0;
       for (idx = 0; idx < size; idx++) {      printf("%d\n", p[idx]);   }
       printf("In print_array function size of array using sizeof: %ld\n", sizeof(p));}
    int main() {   int data[] = {10, 20, 30, 40, 50, 60};
       print_array(data, 3);   /* data = NULL;  What happens if we try this assignment? */
       printf("Size of data array using sizeof: %ld\n", sizeof(data));
       return 0;}

    Code:
    out put is:
    10
    20
    30
    In print_array function size of array using sizeof: 4
    Size of data array using sizeof: 24

  2. #2
    Registered User
    Join Date
    Dec 2015
    Posts
    68
    for (idx = 0; idx < size

    so that is while idx < 3 = 0,1,2

    and that look right as you are asking for 3 units,
    print_array(data, 4); // ask for 4 units 0-3

  3. #3
    Registered User
    Join Date
    Dec 2015
    Posts
    112
    Think of it saying print 3 elements versus what index to print.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trouble understanding some code please help
    By Shinzu911 in forum C Programming
    Replies: 1
    Last Post: 02-19-2013, 09:01 PM
  2. Trouble understanding the concepts behind the code
    By curlygeek in forum C Programming
    Replies: 10
    Last Post: 10-14-2012, 04:31 AM
  3. Trouble understanding code to calculate sum of n numbers
    By jackloring in forum C Programming
    Replies: 8
    Last Post: 11-13-2010, 04:33 AM
  4. trouble understanding collision detection code
    By silk.odyssey in forum Game Programming
    Replies: 5
    Last Post: 06-16-2004, 02:27 PM
  5. a little trouble understanding
    By zema in forum C++ Programming
    Replies: 3
    Last Post: 11-05-2003, 05:49 PM