Expanding array dynamicly after user enter string in function dynamic_array My Problem seems to be when i try to use the extended array agian in main after i dynamic_array returns true.
After function call i try to print input with printf("main string: %s\n", input) the program will crash. It seems like the *input in main never gets extended.
int dynamic_array(char *input, int *string_current_len){
int string_len = 0;
char temp_c;
input = (char *) malloc(sizeof(char));
if(input == NULL) {
printf("Could not allocate memory!");
exit(1);
}
printf("File to search in: ");
while((temp_c = getchar()) != '\n') {
realloc(input, (sizeof(char)));
input[string_len++] = temp_c;
}
input[string_len] = '\0';
printf("\nYou entered the string: %s\n", input);
printf("length of string is %d.\n", string_len);
*string_current_len = string_len;
return 1;
}
int main(void) {
int string_len = 0;
char *input;
printf("enter #q as filename or word to quit.\n");
if(!dynamic_array(input, &string_len)){
return 0;
}
printf("main string: %s\n", input);
return 0;
}
mallocbeing expansive. But you should think hard about the size requested tomallocand you should usually initialize or clear the freshly allocated memory zone just after themalloc. Don't forget thatmalloccan fail, so test that case too.