I'm trying to write a program that combines all command line arguments into one string.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main(int argc, char *argv[]) {
int i;
char *vector;
size_t length;
i = 0;
while (i < argc) {
length = length + strlen(argv[i]) + 1;
i++;
}
vector = malloc(sizeof(char) * length);
assert(vertor != NULL);
strcpy(vector, argv[0]);
i = 1;
while (i < argc) {
strcat(vector, argv[i]);
i++;
}
printf("%s\n", vector);
free(vector);
return EXIT_SUCCESS;
}
My code compiles and run fine on iMac with gcc, but when I run it on my school system it gives me error message saying "uninitialized variable accessed".
Also, what is the difference between (char *)malloc(sizeof(char) * length) and just malloc(sizeof(char) * length)? We were taught the previous in school, but everyone uses the second one online.
Thank you so much!