Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

Descendent print C array

What is wrong with my program, supposed to print the array's content in descendent order?

Output wanted:

500
400
300
200
100

My code:

#include <stdio.h>
int main() {
int numar[]={100, 200, 300, 400, 500};
int *pnumar;

pnumar=numar;

for (int contor=5;contor>0;contor--)
{
     pnumar--;
    printf("%d 
", *pnumar ) ;
   
}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because you're trying to access unallocated memory. When you do pumar=numar the pointer start pointing to the starting address of array numar and the decrement is causing the loop to access unallocated memory. If you want to access array data in reverse order then simply replace for loop with this

for (int contor=4;contor>=0;contor--){
printf("%d 
", pnumar[contor] ) ;

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...