struct Text{
int length;
char *txt;
};
void print(struct Text myTxt)
{
while ( myT开发者_如何学运维xt.txt < myTxt.txt + myTxt.length )
{
printf("%c", ++myTxt.txt);
}
}
int main()
{
struct Text myText;
char test[] = "long long test text";
myText.length = sizeof (test) / sizeof (char);
myText.txt = test;
print(myText);
gets();
return 0;
}
I know that print function is wrong, but how to fix it.
Your problem is print
modifies the struct passed into it. Specifically, to print each character, you're incrementing myTxt.txt
and then printing that. Your while
loop is also incorrect: myTxt.txt < myTxt.txt + myTxt.length
will always be true if myTxt.length
is greater than zero.
You can fix it like this:
void print(struct Text myTxt)
{
char *txt = myTxt.txt;
while ( txt < myTxt.txt + myTxt.length )
{
printf("%c", *txt++);
}
}
This sets txt
to myTxt.txt
, so you can modify txt
without modifying myTxt.txt
.
Assuming myTxt.length
is greater than zero, myTxt.txt < myTxt.txt + myTxt.length
is always true.
So your while loop never terminates.
[Edit]
Well, I suppose it terminates once the addition overflows an int. Still probably not what you intended.
This should be alright:
void print(struct Text myTxt) {
printf("%s", myTxt.txt);
}
(This of course requires myTxt.txt to be null-terminated but for c string this is common anyway.)
So unless your string should be able to contain additional null bytes you could change your code to this:
struct Text{
char *txt;
};
void print(struct Text myTxt)
{
printf("%s", myTxt.txt);
}
int main()
{
struct Text myText;
myText.txt = "long long test text";
print(myText);
return 0;
}
You can get the string's length by calling
strlen(myTxt.txt);
which IIRC requires:
#include string.h
Try:
void print(struct Text myTxt)
{
int i = 0;
while (i < myTxt.length )
{
printf("%c", myTxt.txt[i]);
i++;
}
}
What you did wrong: you printed the addresses of each character, and incrementing it.
what mytxt.txt
is doing is mytxt.txt = mytxt.txt + 1;
therefore you are creating an infinite loop when you are checking the argument for the while loop.
If you need to support NULL bytes:
#include <ctype.h>
#include <stdio.h>
void print(struct Text *myTxt)
{
int i;
for (i = 0; i < myTxt->length; i++)
{
if (isprint(myTxt->txt[i]))
{
printf("%c", myTxt->txt[i]);
}
else
{
int num = (int)((unsigned char)myTxt->txt[i]);
printf("\\%x", num);
}
}
}
If you don't:
#include <stdio.h>
void print(struct Text *myTxt)
{
printf("%s", myTxt->txt);
}
精彩评论