So I struggle since a long time with a (I guess simple) problem with strings in C.
I want to create a list of char pointers and allocate by malloc() each of them some memory to fill with a single random character. At last I want to sort them and build up a new string with strcat().
So in this code only the first part is shown with some testfunctions:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Error, too few arguments!\n");
return 0;
}
// initialize random generator
srand((unsigned int)time(NULL));
const int a = atoi(argv[1]);
char *array[a];
//--------------- generate random characters ----------------------------------------
for (int i = 0; i < a; i++) {
int r = rand() % 30 + 1;
printf("%d ", r);
array[i] = (char*)malloc(a + 1 * sizeof(char));
sprintf(array[i], "%ls", &r);
*(array[i] + 1) = '\0';
}
putchar('\n');
printf("%d %d %d \n", *array[0], *array[1], *array[2]);
char *array_2 = (char*) malloc(a * sizeof(char));
strcat(array_2, *array);
strcat(array_2, *(array + 1));
strcat(array_2, *(array + 2));
printf("Address array_2[0] : %p , value: %d \n", array_2, *array_2);
printf("Address array_2[1] : %p , value: %d \n", &array_2[1], array_2[1]);
printf("Address array_2[1] : %p , value: %d \n", &array_2[2], array_2[2]);
// produces a lot a garbage and crap
printf("array_2 with string : %s :\n", array_2);
// rest of the code omitted because it is irrelevant to the issue
return 0;
}
So, what I don't understand: Printing the characters separately works fine. If I want to print the whole thing as a string, I only get a noisy string of characters. How can I realize the idea?
Honestly, I don't get the problem - if I create a character array like char array[4] = {'a','b','c', '\0'} I can print the whole thing with "%s"... But in my program it is almost the same but doesn't work.
I would be glad if somebody could give me a hint!