0
votes

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

3
charString still doesn't have any memory allocated to it, so how do you expect the copy operation to succeed? You need to use malloc to allocate some heap space for the pointer to point to. - millinon

3 Answers

2
votes

You don't initialize the pointer to point to anything. You can allocate memory on the heap for it using malloc() but make sure you free() it when you are done with it or you will leak memory. For example, alter your original code block to look like this:

/* You need + 1 to store the terminating null character. */
char * charString = malloc(CHARARRAYSIZE + 1);

/* ... */

free(charString);
return EXIT_SUCCESS;
1
votes

You need to allocate space for the characters:

charString = malloc(CHARARRAYSIZE+1);

Later, you need to free them

free(charString);
1
votes

The use of a char array is not helping you here at all.... strcpy(charString,charArray); is still writing to an address that is undefined!

You must have space allocated to scan your data into. That space can be local (such as your local character array) or it can be elsewhere (such as through a malloc() allocation), but it cannot be random as you're currently doing or bad things will happen.