在以下代码的最后一个"for"循环中,我希望在最后一个"for"循环上方以及最后一个"for"循环中分配"tem"的输出相同。但输出是不同的。谁能解释为什么?
我尝试在 while 和 for 循环之间以及最后一个 for 循环中分配 tem。
#include<iostream>
#include<vector>
using namespace std;
void temp(int a[][4],int m,int n,int k){
int temp[m*n];
int row=0,col=0;
int *tem=temp;
int r=m,l=n;
int *start=temp;
while(row<m&&col<n){
int *end=start;
for(int i=row;i<m;i++){
*tem=a[i][col];
tem++;
end++;
}col++;
for(int i=col;i<n;i++){
*tem=a[m-1][i];
tem++;
end++;
}m--;
for(int i=m-1;i>=row;i--){
*tem=a[i][n-1];
tem++;
end++;
}n--;
for(int i=n-1;i>=col;i--){
*tem=a[row][i];
tem++;
end++;
}row++;
if(end-start>k){reverse(start,k,end-1);
start=end;
}}
for(int i=0;i<r*l;i++){
tem=temp;
cout<<*tem<<" ";
tem++;
}
}
void reverse(int *start,int k,int *end){
int *s=start;
int *e=start+k-1;
while(s<e){
int tem=*s;
*s=*e;
*e=tem;
s++;e--;
}
s=start+k; e=end;
while(s<e){
int tem=*s;
*s=*e;
s++;e--;
}
s=start; e=end;
while(s<e){
int tem=*s;
*s=*e;
*e=tem;
s++;e--;
}
}
int main(){
int b[][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};int j=0;
temp(b,4,4,3);
}
如果 tem 的分配在内部13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13我期待13 14 15 16 12 8 4 3 2 1 5 9 7 6 10 11如果我在 while 和 for 循环之间分配 TEM,这就是输出。
在此代码中
for (int i=0; i<r*l; i++)
{
tem = temp;
cout<< *tem << " ";
tem++;
}
每次循环中,tem
都指向 temp
数组的开头。因为打印 tem
的值时总是指向 temp
数组的开头*tem
所以您总是看到相同的值输出。
但是在这个代码中
tem = temp;
for (int i=0; i<r*l; i++)
{
cout << *tem <<" ";
tem++;
}
tem
仅在循环之前分配给temp
数组的开头一次。然后在循环中,tem
递增,以便它指向temp
数组的下一个元素。因此,由于每次循环时tem
都指向temp
数组的不同元素,因此您会看到打印的不同值。