-2

Please be aware that I am new to C. I am coding a function that receives a number and returns a *char formed by '*' of the received length. i.e:

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

I've coded it like this, but it's not working:

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

Any help would be highly appreciated. Thank you so much

Toby
  • 9,696
  • 16
  • 68
  • 132
dev
  • 506
  • 6
  • 16

3 Answers3

4

Two major problems:

char *hidden[length];

This defines hidden as an array of pointers to char. It could be an array of strings, not a string itself.

Then you attempt to return a pointer to this array, but the array is a local variable that goes out of scope and will cease to exist once the function returns. Using the returned pointer will then lead to undefined behavior.

The simplest solution is to pass the buffer to be filled as an argument. Something like

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

Of course remember to create a buffer big enough to hold the full string including the null terminator (which you don't add now).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

You need to use dynamic memory allocation as below

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;
}

Make sure you need to free the memory after done with hidden variable.

char *ptr = createHiddenName(10);
//....
// Use ptr
//....
// done ? then free it 
free(ptr);
ptr = NULL;
Ajay
  • 2,483
  • 2
  • 16
  • 27
0

In your original approach, you have,

   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.

Instead you can follow the below approach.

#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;
}
sjsam
  • 21,411
  • 5
  • 55
  • 102