I am trying to make a function which puts '.'
characters in each string of an array, to complete them to n
characters.
And it is working fine, except that i cannot copy the tmp
sting to the string in the array neither with strcpy, nor with pointers.
The code is:
void foo (char **t, int count, int n) {
int max = 0, i, j;
char *tmp;
for (i = 0; i < count; i++) {
if (max < strlen (t[i])) max = strlen (t[i]);
}
if (max > n) return;
for (i = 0; i < count; i++) {
int diff = n - strlen (t[i]);
tmp = (char *) malloc (diff * (sizeof (char) * n + 2));
for (j = 0; j < diff; j++) {
tmp [j] = '.';
}
tmp [j] = '\0';
strcat (tmp,t[i]);
t[i] = (char *) realloc (t[i], strlen (tmp) + 10);
strcpy (t[i], tmp);
//*(t + i) = *tmp; <- I tried this method too
free (tmp);
}
}
So it is running well (concatenates the two strings), until the strcpy (t[i], tmp);
command.
What am I doing wrong?
(I know, I reserve unnecessarily big space, I do it to be sure.)
The main ()
function in which i use it is:
int main()
{
char *t[3] = {"string", "foo", "help"};
int i;
foo(t, 3, 10);
for (i = 0; i < 3; ++i)
printf("%s\n", t[i]);
return EXIT_SUCCESS;
}
It gives no compiling error, nor warning.
On running it crashes, and returns -1073741819 (0xC0000005), prints nothing.
I am using CodeBlocks.