0

I'm trying to make a program where a user inputs a string then if they want to enter a letter they want to replace and what with. I want to use malloc to set the array but how would I do it with scanf?

Please can someone help.

Thanks!

This is what the program looks before going to the replace method:

char *s,x,y;

printf("Please enter String \n");
scanf("%s ", malloc(s));

printf("Please enter the character you want to replace\n");
scanf("%c ", &x); 

printf("Please enter replacment \n");
scanf("%c ", &y);

prinf("%s",s);
2
  • 1
    I think you want POSIX getline() (not part of the C99 Standard). Commented Apr 1, 2014 at 11:46
  • Your use of malloc is horribly wrong: Malloc takes the number of bytes and returns a pointer. You pass it a pointer. Commented Apr 1, 2014 at 11:58

2 Answers 2

1

You can't know the size of the user input beforehand, so you need to dynamically allocate more memory if the user input hasn't ended yet.

An example would be:

//don't forget to free() the result when done!
char *read_with_alloc(FILE *f) {
    size_t bufsize = 8;
    char *buf = (char *) malloc(bufsize);
    size_t pos = 0;

    while (1) {
        int c = fgetc(f);

        //read until EOF, 0 or newline is read
        if (c < 0 or c == '\0' or c == '\n') {
            buf[pos] = '\0';
            return buf;
        }

        buf[pos++] = (char) c;

        //enlarge buf to hold whole string
        if (pos == bufsize) {
            bufsize *= 2;
            buf = (char *) realloc((void *) buf, bufsize);
        }
    }
}

A pragmatic alternative solution would be to limit the buf size (for example, to 256 characters), and to make sure that only that number of bytes is read:

char buf[256]; //alternative: char *buf = malloc(256), make sure you understand the precise difference between these two!
if (scanf("%255s", buf) != 1) {
   //something went wrong! your error handling here.
}
Sign up to request clarification or add additional context in comments.

Comments

0
scanf("%s ", malloc(s));

What does this mean? s uninitialized is pointer, it can have any value, say 0x54654, it is Undefined Behavior.

Your code should be,

int size_of_intput = 100; //decide size of string
s = malloc(size_of_intput);
scanf("%s ", s);

2 Comments

You should always make sure that no buffer overflows are caused. A >= 100-character user input might very well cause a heap corruption with your code! Pass scanf("%99s ", s) instead, and check the return value of scanf.
@mic_e Great advice. Not knowing %99s possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.