反向功能无法正常运行

问题描述 投票:2回答:2

我试图找出程序:“写一个函数反方向(S),其反转characte字符串s使用它来编写反转其输入在时间线的程序。”

我以为伪代码类似下面应该工作:

“复制字符串s TMP,同时提高迭代器。复制串tmp目录S,同时降低初始迭代器,增加了新的”

#include <stdio.h>

void reverse(char []);

int main(){
    char string[50]="HelloWorld";
    printf("Consider Given string: %s\n",string);
    reverse(string);
    printf("The same string, reversed: %s\n",string);
}

void reverse(char s[]){
    char tmp[50];
    int i,j;
    for (i=0;(tmp[i]=s[i])!='\0';++i);
    for (j=0;i>0;i--,j++)
        s[j]=tmp[i];
}

作为输出,我得到:

pi@readonly:~/new$ a.out
Consider Given string: HelloWorld
The same string, reversed: 

当使用gdb调试,注意到以下几点:

Breakpoint 5, reverse (s=0x7efff5a4 "HelloWorld") at 1.c:18
18                              s[j]=tmp[i];
1: j = 0
2: i = 10
3: tmp = "HelloWorld", '\000' <repeats 15 times>, "\360\377v\334\365\377~\340\372\353v\000\000\000\000\224\365\377~,\006\001\000\300\004"
4: s = 0x7efff5a4 "HelloWorld"
(gdb) n
17                      for (j=0;i>0;i--,j++)
1: j = 0
2: i = 10
3: tmp = "HelloWorld", '\000' <repeats 15 times>, "\360\377v\334\365\377~\340\372\353v\000\000\000\000\224\365\377~,\006\001\000\300\004"
4: s = 0x7efff5a4 ""
(gdb) n

Breakpoint 5, reverse (s=0x7efff5a4 "") at 1.c:18
18                              s[j]=tmp[i];
1: j = 1
2: i = 9
3: tmp = "HelloWorld", '\000' <repeats 15 times>, "\360\377v\334\365\377~\340\372\353v\000\000\000\000\224\365\377~,\006\001\000\300\004"
4: s = 0x7efff5a4 ""

问题:

1)为什么字符串元素tmp突然从字符串s消失字符串中列出,在点,当i=0,但是,在那里,在这之前的步骤?换句话说,发生了什么字符串s,在断点处17,for (j=0;i>0;i--,j++)

2)是否有可能声明和相同for循环中分配不同的功能的类型,利用逗号?换句话说,为什么下面的建设给错误,而试图编译?有没有一种方法,以燎循环中使用不同的标识符类型?

施工:

void reverse(char s[]){
    for (char tmp[50],int i=j=0;(tmp[i]=s[i])!='\0';++i);
    for (j=0;i>0;i--,j++)
        s[j]=tmp[i];
}

错误:

pi@readonly:~/new$ cc 1.c
1.c: In function ‘reverse’:
1.c:14:21: error: expected identifier or ‘(’ before ‘int’
for (char tmp[50],int i=j=0;(tmp[i]=s[i])!='\0';++i);
                 ^~~
1.c:14:36: error: ‘i’ undeclared (first use in this function)
for (char tmp[50],int i=j=0;(tmp[i]=s[i])!='\0';++i);
                                ^
1.c:14:36: note: each undeclared identifier is reported only once for each function it appears in
1.c:15:8: error: ‘j’ undeclared (first use in this function)
for (j=0;i>0;i--,j++)
    ^
1.c:16:9: error: ‘tmp’ undeclared (first use in this function)
s[j]=tmp[i];
c kernighan-and-ritchie
2个回答
3
投票

在这个循环的开始:

for (j=0;i>0;i--,j++)
    s[j]=tmp[i];

tmp[i]包含在字符串末尾终止空字节。所以,你是空字节复制到s的开始,给你一个空字符串。

索引i当从tmp的值减去1。这样一来,你就开始处的第一个上赛季常规字符和结尾。

for (j=0;i>0;i--,j++)
    s[j]=tmp[i-1];

1
投票

A C-字符串以\0字符终止,并且您reverse功能拷贝从源字符串的末尾该字符串终止字符到开始目标串的。目标字符串将是“空”的话,因为它是正确的,在年初结束。

你必须要考虑两件事情:

首先,访问tmp时候开始一个结束之前:

for (j=0;i>0;i--,j++)
    s[j]=tmp[i-1];

其次,要确保目标字符串被终止。如果目标字符串是一样的源字符串,什么都不依然做因为\0已经到位。

如果你以某种方式复制到不同的目标,你必须在循环后写s[j]='\0'

© www.soinside.com 2019 - 2024. All rights reserved.