#include%26lt;stdio.h%26gt;
main()
{int mas[5]={0};
int *p;
int i;
p=mas;
system("cls");
i=0;
do
{
*(p+i)=i;
i++;
printf("\n mas[%d]=%d",i,*(p+i));
}while(i%26lt;5);
}
So, when i compiel it, it shows me something like
mas[1]=21424
mas[2]=125215
.....
mas[5=21215 %26lt;%26lt;%26lt;?????why` that??
and I thought, that it would be sometnhing like
mas[1]=0
mas[2]=1
and so on...why isn`t it???
Ok, C language once more?
You don't give details about your environment (OS, Compiler, Debur ou Build mode, ...) but
initialization is incomplete:
int mas[5] = {0,0,0,0,0} is the code required to init all elements of he array (at least in my compiler ...)
However this has no impact on the following code ...
Arrays in C and C++ are zero-based, meaning that the first element is mas[0] and not mas[1];
You need to swap the line 'i++' and the line 'printf...'
You init the mas[0] and display the mas[1] BEFORE it is initialized because it is init in the next round of the do while loop ...
Here is the code
i = 0;
do
{
*(p+i)=i;
printf("\n mas[%d]=%d",i,*(p+i));
i++;
}while(i%26lt;5);
Thierry
Web: www.tgmdev.be
Download Isanaki 2.1a at www.tgmdev.be, the last version of Isanaki, a free Sudoku and Wordoku Generator, Solver and Helper ...
Reply:Actually the arror is here : *(p+i)=i;
you dont have to increment it directly.Since you have passed the address of array mas to p.It will increment with each assigning.
You got the error early because the integer value addess will increment by 2 each time since integer value has 2 bits.
Here is the corrected code
#include%26lt;stdlib.h%26gt;
#include%26lt;stdio.h%26gt;
#include%26lt;conio.h%26gt;
void main()
{int mas[5]={0};
int i=0;
int *p;
p=mas;
system("cls");
do
{
*(p)=i++;
printf("\n mas[%d]=%d",i,*(p));
}while(i%26lt;5);
getch();
}
brenda song
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment