1. ## Returning pattern

Hi
I am writing programm to print pattern like below
1
22
333
4444
55555
666666
up to n given as a parametr.
my code below
Code:
```char* pattern(const int n)
{
char *result = (char*)malloc(sizeof(char)*n*n*n*n);
char *temp = (char*)malloc(sizeof(char) * 4);
memset(result, '\0', (n*n*n*n));
if (n<1)
return "";
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
sprintf(temp, "%d", i);
strcat(result, temp);
}
strcat(result, "\n");
}
result[strlen(result) - 1] = '\0';
return result;
}```
I pass all basic test but on random test i got some errors. Can you tell me where is mistake 2. How big can n be?

Your code leaks memory all over the place. 3. Originally Posted by Salem How big can n be?
maximum n size is 2^16 which give us 65 536 so n should be at least 5 characters long Originally Posted by Salem Your code leaks memory all over the place.
I thought that I don't have to calculate perfect value of characters for each n thats why I allocated bigger memory than I need 4. Originally Posted by gawiellus maximum n size is 2^16 which give us 65 536 so n should be at least 5 characters long
Then, it is not possible with your code... result will have to point to a buffer which requires 2^64 bytes ( 1 EiB ). 5. This is task from codewars site so probably n is correct value.
So the way is to calculate perfect bytes of allocated memory? For example
Code:
```if(n<9)
size=n*(n+1)/2;
if(n>9&&n<=99)
size=2*(n*(n+1)/2)+(n+1)/2
if(n>99&&n<=999)
size=3*(n*(n+1/2)+2*(n*(n+1)/2)+(n+1)/2``` 6. temp is the one leaking memory since you don't free it before the function ends.
However, it's pointless for it to be dynamic anyway.

For n = 65536, result must be 10,687,148,122 bytes.

If you just have to print it, why are you making a string?
Why not just
Code:
```for (int i = 1; i <=n; ++i) {
for (int j = 0; j < n; ++j)
printf("%d", i);
putchar('\n');
}``` 7. Sorry I probably said wrong my task is not print but return as a string. If memory is limited than probably n must be lower than 65536. As I said this is task from codewars site then n must be correct value. 8. ## Code:
```#include <stdio.h>

int printPattern(int n) {
for (int i = 0; i < n; i++) {
printf("%i",n);
}
}

void numberTree(int n) {
for (int i = 1; i < (n+1); i++) {
printPattern(i);
printf("\n");
}
}

int main() {
numberTree( 9 );
return 0;
}``` Popular pages Recent additions char, code, parametr, pattern, patternconst 