Keeping your logic to have one last empty element.
You want an array of char *
so you need to allocate size * sizeof(char *)
You need memory for scanf and check the returned value
Then you need to copy the scan string, using strdup
for example
A list can be better for your case
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char** append(char** b, size_t* size, const char* target);
int main(){
size_t size = 1;
char** b = malloc(sizeof(char*)*size);
while(1){
char input[256];
int res = scanf("%s", input);
if (res == EOF || strcmp(input, "end") == 0)
break;
b = append(b, &size, input);
}
for(int i = 0; i < size; i++)
printf("%s ", b[i]);
printf("
");
return 0;
}
char** append(char** arr, size_t* _size, const char* target){
size_t size = *_size;
arr[size - 1] = strdup(target);
size++;
char** new_arr = realloc(arr, size * sizeof(char *));
*_size = size;
return new_arr;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…