I have to input a string and display it to standard out put.
The ideal solution would be to acquire the string into a char pointer array, however I get an error on the scanf, I presume because the char pointer string solution there is no space allocated for it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *charString;
printf("Input string - max %i caratteri: ",CHARARRAYSIZE);
scanf("%s", charString);
printf("%s",charString);
return EXIT_SUCCESS;
}
Therefore I resorted to acquiring the sting into into a char array and then copy (strcpy) into a char pointer string.v In this case I get a warning saying that on the strcpy call sayng that strcpy is used without being initalized. How do I fix this?
Please find below the code for this second case.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CHARARRAYSIZE 16
int main(void) {
char *charString;
char charArray[CHARARRAYSIZE];
printf("Input string - max %i characters: ",CHARARRAYSIZE);
scanf("%s", charArray);
strcpy(charString,charArray);
printf("%s",charString);
return EXIT_SUCCESS;
}
Is there any way to achieve my aim and avoid using a char array
charStringstill doesn't have any memory allocated to it, so how do you expect the copy operation to succeed? You need to usemallocto allocate some heap space for the pointer to point to.