【发布时间】:2022-01-08 09:09:34
【问题描述】:
我现在正在学习 C,我的程序中有一个问题。
我需要反转字符串,例如I like dogs -> I ekil sgod
我写了这段代码
char end[MAX_LEN];
char beg[MAX_LEN];
char* piece = strtok(str, " ");
strcpy(end, piece);
strcpy(beg, piece);
char* pbeg = beg;
char* prev = piece;
int n = strlen(piece)-1;
i = 0;
int n = 0;
while (piece != NULL) {
//printf("\n%s", piece);
while (piece[i] != '\0') {
*(prev + n -i ) = *(pbeg + i);
i++;
}
printf("\n%s", piece);
piece = strtok(NULL, " ");
strcpy(beg, piece); // also in this moment in debugging i saw this error ***Exception thrown at 0x7CBAF7B3 (ucrtbased.dll) in лаб131.exe: 0xC0000005: Access violation reading location 0x00000000.***
}
但它只返回第一个反转的词位。
【问题讨论】:
-
strcpy(beg, piece);将在strtok循环的最后一次迭代中失败(取消引用NULL指针)。 -
@Anchr 代码没有意义。
-
@Anchr 看到这个问题stackoverflow.com/questions/69784686/…
标签: c loops char reverse c-strings