#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct {
int elem[MAXSIZE];
int last;
} seqlist;
int main() {
seqlist L;
L.last = 0;
int i;
for (i = 0; i < 20; i++)
;
{
L.elem[i] = i;
L.last++;
}
cout << "The value of L:" << ' ';
for (i = 0; i < 20; i++) {
cout << L.elem[i] << ' ';
}
cout << "\n"
<< "The last of L:" << ' ';
cout << L.last << endl;
return 0;
}
This is the result
The value of L: 1876269952 0 4206312 0 4206304 0 661232 0 6421936 0 16 0 8 0 0 0 0 0 1876144503 0
The last of L: 1
I don't know why this happens. Please help me.
It's hard to notice but you've got a semicolon right after your for
loop:
for (i = 0; i < 20; i++); <-----
This means the loop runs 20
times and executes an empty statement. At the end of the loop i
is 20
, so the following statements only work on L.elem[20]
. Then when you print the values you're just printing the initial garbage values instead of what you expected.
Remove the semicolon and your code works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.