0
#include<stdio.h>
#include<string.h>
#include<malloc.h>
char *str_rev(char s[]){
 static char *st = NULL;
 static char *l;
 int i = 0,c = 0;
 st = malloc((strlen(s) * sizeof(*s))+1);
 *l = st;
 if(s == NULL){
  return "INVALID PARAMS";
 }
 for(i=0;s[i]!='\0';i++){
 ;
 }
 for(c=i;c >=0;c--){
  *l++ = s[c];
 }
 l = '\0';

 return st;
}
int main(){
 char a[]="Angus Declan R";
 printf("\n %s \n",str_rev(a));
 return 0;
}

逆の文字列を再実行する必要があるため、func str_rev()でmalloc()を使用して割り当てられたメモリを解放する方法。

4

1 に答える 1

5

(1):最初のメモリインl\0、何も出力しない理由である次の理由によるものです。

ループの後

for(i=0;s[i]!='\0';i++){
 ;
 }

s[i]になり \0、割り当てます。c=i次の2番目のループでは\0、の最初のポイントで割り当てますl

for(c=i;c >=0;c--){
  *l++ = s[c];  // you are assigning `\0` for first time
 }

あなたは戻っreturn l;てきて、最初の位置l \0はそうです。%s

printf("\n %s \n",str_rev(a));    

何も印刷しません。

提案:

for(c=i-1;c >=0;c--){
     // ^ c should be i-1 initially 
  *l++ = s[c];
 }

(2):少なくとも質問コードに2つのコンパイルエラーがあります。;あなたは2つのポジションを忘れました

 return "INVALID PARAMS"; 
                        ^ 

char a[]="Angus Declan R";
                         ^

3番目の重大な間違い

無効なメモリアドレスを返しています!
あなたがしていること、でメモリをst割り当て、次にに割り当てlfree(st)そして戻るl:(コメントを読む

st = malloc((strlen(s) * sizeof(*s))+1);   // allocation 
l = st;          // assign to l

// code in between

free(st);    // st and l become invalid after free
return l;    // returning invalid memory 

提案: free()を呼び出さず に、 作業しlて戻ってきますか?st

(4)

これはエラーではありませんが、なぜこの役に立たないループなのですか?

while(c > 0){
  l--;
  c--;
 }

(5):前に*忘れたl

for(c=i;c >=0;c--){
  *l++ = s[c];
 }
  l = '\0';
 ^ forgot *   it should be *l = '\0';
于 2013-03-09T19:15:47.973 に答える