Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array doesn't print in reverse in C using pointers

I am trying to make a program that takes 10 numbers as input and outputs them in reverse order using pointers in C.

    #include<stdio.h>
    #define N 10

    int array[N]; //Global variable


    int main(void) {
    int j;
    int i;

    printf("Enter 10 numbers: ");

    for (i=0;i<N;i++) {
          scanf("%d",(array+(4*i)));    //Works
    }

    for (j=N-1;j<0;j--) {
       printf("%d",array[j]);  //Doesn't print, using *(array+j*4) doesn't 
                                                           //print  also
    }

    printf("\n");
    printf("%d\n",*(array)); //Works so scanf works
    printf("%d\n",*(array+4)); //Works so scanf works
    return 0;

    }

I have tried a making a seperate function for the two for loops but still it doesn't work. I want to know WHY this for-loop doesn't print but the two printfs below it print.

EDIT:

My new code is

    #include<stdio.h>
    #define N 10

    int array[N]; //Global variable


    int main(void) {
    int j;
    int i;

    printf("Enter 10 numbers: ");

    for (i=0;i<N;i++) {
          scanf("%d",(array+i));    //Works
    }

    for (j=N-1;j<0;j--) {    //it is supposed to be j>=0 or j>0 WHY
       printf("%d",array[j]);  //Doesn't print, using *(array+j) doesn't 
                                                           //print  also
    }

    printf("\n");
    printf("%d\n",*(array)); //Works so scanf works
    printf("%d\n",*(array+1)); //Works so scanf works
    return 0;

    }

Thanks to all the posts, I have a better understanding of how indexing works in C now but the printf doesn't work still unless I change the for-loop conditions(see above). WHY doesn't it work with the initial conditions but with the latter conditions.

like image 745
Nameless Avatar asked Dec 21 '22 03:12

Nameless


1 Answers

Whoa!

This:

scanf("%d",(array+(4*i)));    //Works

is very wrong and is overwriting memory! Why are you multiplying the index? You don't need to do that, C can index by itself. It should just be:

scanf("%d", &array[i]);

You want the address of the i:th array member, so say that, don't beat around the bush with strange multiplications.

If you really want to be "using pointers", as mentioned in a comment, you can do so:

scanf("%d", array + i);

This works since array is a pointer to the first element of the array, and adding i to is a fully valid use of pointer arithmetic; C will compute the proper pointer, knowing the size of each int in the array.

like image 195
unwind Avatar answered Dec 22 '22 16:12

unwind