0

I have a function that makes a string with a certain number of #. String is stored as in char array (at list I think this is it... I'm new to C). This string is generated inside a function called blocks. I want to know how to return it so I can display it with printf("Someting Something %s", bricks) Do I have to change data type of ma string to char or how do I change the code to work?

int main(void)
{
    char hashes = blocks(3);
}

char blocks(int n)
{
    // string in which I will store data
    char line[] = ""; 
    int max = n + 1;
    for (int i = 0; i < max; i++)
    {
        // n times # is appended to char array line
        char brick[] = "#";
        strcat(line, brick);
    }
    return line;
}

I want to know how to return string or array ### and store it in variable hashes.

  • 1
    @klutt this dupe does not cover all problems of this "code" – 0___________ Feb 12 '22 at 17:47
  • The main point is that C doesn't handle strings as a native type like java does. The line `char line[]=""` just allocate one byte of memory set to `'\0` (end of C string). Really you may want have a look to a C book/tutorial. – Frankie_C Feb 12 '22 at 17:52

1 Answers1

-1

Plenty problems.

  1. line is not long enough to accommodate additional characters added by strcat. Actually, it can only accommodate null terminating character
  2. You cant return the pointer to the local variable as this variable stops existing when the function returns.
  3. Your function returns the char not char * pointer. So the pointer is being converted to int
  4. hashes is assigned a nonsense value as per p3

I think you need to start from the C book.

0___________
  • 60,014
  • 4
  • 34
  • 74