Thread: What is the best way to use pointers for manipulating array elements?

  1. #1
    Registered User zolfaghar's Avatar
    Join Date
    Mar 2016
    Posts
    95

    What is the best way to use pointers for manipulating array elements?

    I was looking at the following question from Let us C. While my code seems to work, I wonder if there is a cleaner more organized way I can do this. A way with less variables or fewer lines of code. Here is the problem given:

    Write a program which performs the following tasks:
    - initialise an integer array of 10 elements in main()
    - pass the entire array to a function modify()
    - in modify() multiply each element of array by 3
    - return the control to main() and print the new array elements in main()

    Here is what I have:

    Code:
    #include <stdio.h>
    int main ()
    {
      int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      int *i, l;
      int modify();
      i = &arr[0];
      //printf("%d", *i);
      modify (i); 
      for ( l = 0 ; l < 10 ; l++)
        {
           printf("\nHere is the array after modification  %d\n", *i);
           i++;
        }
    }
    
    int modify (int *j)
    {
    int k;
    for ( k=0 ; k < 10; k++)
      {
          *j = (*j) * 3;
          //printf ("\nHere is what is in arr%d \n", *j);
          j++;
      }
    
    }

    Here is the output:


    Here is the array after modification 3

    Here is the array after modification 6

    Here is the array after modification 9

    Here is the array after modification 12

    Here is the array after modification 15

    Here is the array after modification 18

    Here is the array after modification 21

    Here is the array after modification 24

    Here is the array after modification 27

    Here is the array after modification 30

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I suggest:
    Code:
    #include <stdio.h>
    
    void modify(int *numbers, size_t size);
    
    int main(void)
    {
        int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        size_t numbers_size = sizeof(numbers) / sizeof(numbers[0]);
        size_t i;
    
        modify(numbers, numbers_size);
    
        printf("Here is the array after modification:\n");
        for (i = 0; i < numbers_size; i++)
        {
            printf("%d ", numbers[i]);
        }
        printf("\n");
    
        return 0;
    }
    
    void modify(int *numbers, size_t size)
    {
        size_t i;
        for (i = 0; i < size; i++)
        {
            numbers[i] *= 3;
        }
    }
    Notice that:
    • I forward declared modify before the main function. Unless you have some special reason for forward declaring a function more locally, this is the usual convention.
    • modify now takes both a pointer to the first element of the array of numbers, and also the number of numbers, i.e., the size. Furthermore, I used more descriptive names, i.e., numbers and size.
    • Since modify does not return a value, I changed its return type to void.
    • I renamed arr to numbers in main. This is just stylistic.
    • I got rid of the unnecessary i pointer in main. You can use numbers instead of i, after all.
    • l tends to be a poor variable name, one reason being that in some fonts, it is difficult to distinguish from I. I renamed it to i and changed its type to size_t since it will be compared to numbers_size, which is a size_t by virtue of being initialised with a computation involving the result of sizeof.
    • I changed the print out format to something that makes more sense to me.
    • I added a return 0 at the end of main, but this is optional if you are compiling with respect to C99 or later.
    • In modify, notice my use of the multiplication and assignment operator. I also dispensed with the pointer notation since array notation will do.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User zolfaghar's Avatar
    Join Date
    Mar 2016
    Posts
    95
    Quote Originally Posted by laserlight View Post
    I suggest:
    Code:
    size_t numbers_size = sizeof(numbers) / sizeof(numbers[0]);
    Thank you so much. I was wondering about above line, so I printed it out. I think sizeof function returns the total number of bytes in an array if you pass the name without the []s. Is that right? And if you add the brackets with an index number, it then would return the size of each array element? I guess you do it this way to get the size of the array regardless of the architecture?

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by zolfaghar
    I think sizeof function returns the total number of bytes in an array if you pass the name without the []s. Is that right?
    Yes, except that sizeof is an operator, not a function. This distinction would be most evident when you see code like this:
    Code:
    size_t numbers_size = sizeof numbers / sizeof numbers[0];
    Though I prefer to leave the parentheses in since they are required when the operand is a type name rather than an expression.

    Quote Originally Posted by zolfaghar
    And if you add the brackets with an index number, it then would return the size of each array element?
    Yes, but that's because "add the brackets with an index number" just gives you an element of the array, in this case the first element. Since all the elements are of the same size in bytes, choosing the first is as good as any.

    Quote Originally Posted by zolfaghar
    I guess you do it this way to get the size of the array regardless of the architecture?
    Yes.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointers and printing distinct elements in array
    By dave_the_bear10 in forum C Programming
    Replies: 2
    Last Post: 10-29-2011, 01:31 AM
  2. Accessing elements in an array of pointers to arrays
    By fxtdr79 in forum C Programming
    Replies: 5
    Last Post: 06-05-2010, 09:29 PM
  3. printing elements of an array using pointers
    By zeebo17 in forum C Programming
    Replies: 3
    Last Post: 05-22-2009, 09:30 PM
  4. Manipulating private individual char elements
    By Know_Your_Role in forum C++ Programming
    Replies: 4
    Last Post: 03-31-2009, 01:18 PM
  5. Replies: 3
    Last Post: 10-14-2001, 01:13 PM

Tags for this Thread