-5

我在 Ansi C 中有这个问题

3 创建一个函数,该函数接收每个解码的 20 个字符的字符串数组,考虑以下几点:从左到右读取它,数字表示从那里要投入多少个字符(要投入的字符之间可以是数字,因此,被认为是普通字符)。
湾。数字字符应替换为反转字符串的第一个字符。

例子。字符串 aj5pr2*dfkl3abc2qwe1azk 必须是 ajd*2rpfklcbawqeazk

使用符号和指针算术

#include <stdio.h>
#include <string.h>

#define TAM 20


char* invertNumerSubstrings(char*);

int main()
{
    char chain[TAM];
    printf("\n Ingrese chain: ");
    gets(chain);
    fflush(stdin);
    char result;
    result=invertNumerSubstrings(chain);
    printf("\n Chain modified: ");
    puts(chain);
    printf("\n");   
    return 0;
}

char* invertNumerSubstrings(char* chain)
{
    int flag =0;
    char *pl= chain;
    char *pe= chain;
    char aux;
    while(*pl=='\0'&& *pe=='\0');
    {
        if(!(*pl=='1')&&(*pe=='9'))
        {
            pl++;
            pe++;
        }
        else
        {

            if(flag ==0)
            {
                pe=*pl;
                flag=1;
                pl--;
            }
            if(*pe<*pl)
            {
                aux=*pl;
                *pl=*pe;
                *pe=aux;
            }
        }
    }
    return *chain;
}

这个程序没有编译错误,但没有工作

4

2 回答 2

1

当我尝试它时,这有编译器警告 -main()你已经声明了

char result; result=invertNumerSubstrings(chain);

但是那个函数是 type 的char*。但是你甚至不使用result.

更严重的是,在您放置的函数中while(*pl=='\0'&& *pe=='\0');注意错误的尾随如果没有内容,;该语句将永远执行,否则只会执行一次,之后以下代码块将仅执行一次。chain

于 2014-10-24T20:14:47.533 回答
1

您的代码中有很多问题。指点其中的一些。在功能main()

char result;
result=invertNumerSubstrings(chain);

invertNumerSubstrings函数的返回类型与' 的类型char*不匹配。result

while(*pl=='\0'&& *pe=='\0');

;上面的语句在逻辑上是不正确的,如果条件得到满足,可能会导致循环无限执行。*pl=='\0'&& *pe=='\0'根据问题的需要,情况看起来并不完美(如果我错了,请纠正我)。

return *chain; 

return 语句是invertNumerSubstrings返回类型与 不匹配的函数的最后一条语句char*

要获得所需的输出,您可以尝试以下操作:

void invertNumerSubstrings(char* chain)
{

char *pl= chain;
char* chain_ptr=chain;   // chain_ptr to hold starting address of chain
char* final=(char*)malloc(sizeof(chain));
char* final_ptr=final;  // // final_ptr to hold starting address of final
memset(final, '\0', sizeof(chain));

while(*pl!='\0')
{

    if(*pl>=49 && *pl<=57) //
    {   
         int shift=*pl-48; // to find the shift amount
         int i=0;
         *pl++;

         for(i=shift-1; i>=0; i--){
             *final=*(pl+i);
             final++;
         }
       pl=pl+shift;  // seek the pointer to correct position            
    }

     else
         {
              *final=*pl;
               pl++;
               final++;

         }
}

chain=chain_ptr; // assign original address of chain to chain again

while(*final_ptr !='\0'){
      *chain=*final_ptr ;
      final_ptr++;
      chain++;             
}
*chain='\0';

free(final);

}

假设:当在字符串中遇到整数时,其后续字符串的长度至少等于整数值。

于 2014-10-24T20:29:44.320 回答