Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

string - C for loop not working

#include <stdio.h> 
char str[5][10]={"asdasdasd", "", "", "qweqweqwe", "asdasdasd"};

int main (){
change (4, 5, 3, 2);

}


void change (int r1, int c1, int r2, int c2){
int i=0;
for (i=0; i<2; i++){
str[r2][c2+i] = str[r1][c1+i];
}
for (i=0; i<2; i++){
str[r1][c1+i] = ' ';
}
return;
}

str is a 2-d string. when I debug it, the second for loop just Works and deletes those characters, but the first row doesnt work. why?

the error is, when I print the string, the chars at [r1][c1] and [r1][c1+1] is deleted but [r2][c2] and [r2][c2+1] is still empty.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I tried to run that and my outputs for r1 and r2 are

qwdaweqwe

asdas--sd (two spaces)

and basically it is what the code should be doing.

But if I get your intention right, you want to work with those empty strings. Then you should be feeding your function with different numbers, because array indexing works from 0 to n-1, meaning that if you want to use the second empty string, use index 2. I tried that, but there is problem with the declaration. You can try this

char str[5][10] = { "asdasdasd", "         ", "         ", "qweqweqwe", "asdasdasd" };

or some fine malloc for those two empty strings. Code above works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...