Thread: Help, please

  1. #1
    Registered User
    Join Date
    May 2012
    Posts
    12

    Help, please

    ok, so my assignment says I must use *(channels + i) as a pointer.

    No matter how I write out the program, it really does not seem to like that as a pointer. Can anyone point me in the right direction?

    Code:
    #include <stdio.h>
    int channels[7] = {2,4,5,7,9,11,13};
    int *(channels + i);
    
    
    int main(void)
        {
            
            int i;
            channels + i = &channels[]
            display(channels)
                    
            printf("\n\n")
            for(i=0; i<7; i++;)
            {
                     printf("The numbers are[%d] = %d   ",i,display[i]);   
                           }

    I don't even think I'm doing the rest of the program right, but I can't get past the 3rd line to see what else I might be doing wrong. Any ideas?

    Thank you

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You're all kinds of confused, but it's okay, the answer is quite simple. All it is asking you to do is to use "pointer notation" instead of "array notation". In C, the following two statements are equivalent:
    Code:
    some_array[index]
    // and
    *(some_array + index)
    You can't use (*some_array + index) in a declaration, but you can in any assignment/expression. So get rid of the third line, you don't need it at all. Just write your assignment with array notation, then go back and replace every instance that uses the a[i] bracket notation with the *(a + i) pointer notation.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    505
    This is C confusing syntax.

    We have arrays and pointers. In C, they're almost the same. An array is effectively a constant pointer to a memory buffer.

    So you can write

    Code:
    int channels[7];
    
    for(i=0;i<7;i++)
       printf("%d ", channels[i]);
    or you can write

    Code:
    int channels[7];
    int *ptr = channels;
    
    for(i=0;i<7;i++)
      printf("%d ", ptr[i]);
    or you can write

    Code:
    int channels[7];
    int *ptr = channels;
    
    for(i=0;i<7;i++)
      printf("%d ", *ptr++);
    or you can write

    Code:
    int channels[7];
    int *ptr = channels;
    
    for(i=0;i<7;i++)
      printf("%d ", *(ptr + i));
    It's all the same. Which you use depends on what makes more sense. For just stepping through the array, use [] notation. If you want to move forwards and backwards in a complicated way, * notation might be clearer.

Popular pages Recent additions subscribe to a feed