2017-06-22 27 views
-2

請注意,我是C的新手。我編寫的函數接收一個數字,並返回由接收長度的'*'組成的*char。即:用於返回自定義長度字符的C函數

createHiddenName(6)//returns "******" 
createHiddenName(4)//returns "****" 

我編寫它像這樣,但它不工作:

char *createHiddenName(int length) 
{ 
    char *hidden[length];// 
    int i; 
    for (i = 0; i < length; i++) { 
     hidden[i] = '*'; 
    } 
    return *hidden; 
} 

任何幫助將高度讚賞。謝謝你這麼多

+0

'請注意,我是C'.... uummmm..why的新手? –

+0

'char * hidden [length];'...你不需要那個 –

+2

'return * hidden;'......什麼?爲什麼? –

回答

3

您需要使用動態內存分配如下

char *createHiddenName(int length) 
{ 
    char *hidden = malloc((length+1) * sizeof(char)); 
    if(hidden == NULL) { 
    return NULL; 
    } 
    int i; 
    for (i = 0; i < length; i++) { 
    hidden[i] = '*'; 
    } 
    hidden[i] = '\0'; //Null terminated string 
    return hidden; 
} 

確保你需要釋放與hidden變量完成後的記憶。

char *ptr = createHiddenName(10); 
//.... 
// Use ptr 
//.... 
// done ? then free it 
free(ptr); 
ptr = NULL; 
+0

非常感謝。 – dev

+0

'sizeof(char)'是一個定義。 –

0

在你原來的做法,你有,

char *hidden[length]; // Why would you like to have an array of pointers? 
    return *hidden; // Wrong because unless 'malloc'ated, a pointer inside the function will not work after the return, Consider what happens if the function stack is cleared. 

相反,你可以按照下面的方法。

#include<stdio.h> 
#include<string.h> 
char hidden_name[100]; 
// global char array for storing the value returned from function 
char *createHiddenName(int length) 
{ 
      char temp[length+1]; 
      int i; 
      for (i = 0; i < length; i++) { 
         temp[i] = '*'; 
         } 
       temp[i]='\0'; // Null terminating temp 
      strncpy(hidden_name,temp,(size_t)(length+1)); 
      //Remember temp perishes after function, so copy temp to hidden_name 
      return hidden_name; 
} 


int main(){ 
printf("Hidden Name : %s\n",createHiddenName(6)); 
return 0; 
} 
+0

我可以知道什麼是downvote嗎? :) – sjsam

4

兩個主要問題:

char *hidden[length]; 

hidden定義爲的指針char陣列。它可以是字符串的數組,而不是字符串本身。

然後你嘗試返回一個指向這個數組的指針,但是這個數組是一個局部變量,它超出了作用域,並且一旦函數返回就會停止存在。使用返回的指針將導致未定義的行爲

最簡單的解決方法是將要填充的緩衝區作爲參數傳遞。像

char *createHiddenName(int length, char *hidden) 
{ 
    ... 
    return hidden; 
} 

當然東西記住創建大到足以容納完整的字符串包括空終止(你現在不加)的緩衝區。