[英]decoder function returns garbage string in C. how to fix?
以下是我制作的簡化解碼函數,該函數假定采用特定大小的字符串,並以原始字符串中相同位置的每個字符的ascii值小於原始字符的字符串返回該字符串。
例如,如果我使用參數“ BCDEF”和5調用該函數,那么我應該能夠返回“ ABCDE”,但是,我得到的大部分都是垃圾。
char* dec(char* s,int sz){
int x=0;
unsigned char p=0;
char ss[sz];
if (s){
for (x=0;x<sz;x++){
p=s[x];
p=p-1;
ss[x]=p;
}
return ss;
}
else{return s;}
}
這是我從外面打電話的方式:
char *item="BCDEF",*item2=" ";
item2=dec(item,5);
printf("item= %s",item2);
即使我嘗試保留固定大小,也將item2的結果打印為字符串會產生垃圾。
編譯代碼還會產生“警告:函數dec返回本地變量的地址”,但我沒有在變量前加上&。
我將如何解決這個問題?
ss
是dec
函數中的Local(數組)變量。 函數結束時,數組將不復存在,並且稍后您訪問該指針/地址時,其未定義行為 。
而不是將本地數組放在堆棧上,而是對其進行malloc
:
char *ss = malloc(sizeof(char)*(sz+1)); //+1 for NUL char
//do something
return ss;
並在不需要時使用free
清除內存。
嘗試這個:
#include <stdio.h>
#include <stdlib.h>
void dec(char *s, int sz, char *ret)
{
if ( s == NULL )
{
printf ( "\n entered string have NULL value\n " );
exit ( 0 );
}
while ( *s != NULL )
{
*ret = (int)*s - 1 ;
s++;
ret++;
}
*ret = '\0';
}
int main ( void )
{
char * ret = NULL;
ret = (char * ) malloc (5 * sizeof (char ));
dec ("code" , 5, ret );
printf ( "\n %s\n", ret );
free ( ret );
return ( 0 );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.