Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a scanf string from a function

Tags:

c

It shows nothing when you pass the string to the function

int main(void){
    char *string[200];
    getChar(string);//starts function
    printf("This is the string %s",*string);//prints
    return 0;
}

Void getChar(char *String[200]){
    scanf(" %s",String[200]);//gets string
}
like image 901
Nickpost Avatar asked Nov 30 '25 20:11

Nickpost


1 Answers

There are multiple problems:

  • You should use an array of char instead of an array of char *,
  • you should pass the array directly to scanf():
  • Void has no capital: void
  • getChar is confusing to read a string and should be declared or defined before use.
  • the initial space in scanf(" %s", is redundant: %s already skips initial spaces.
  • you must tell scanf() the maximum number of characters to store into the destination array, otherwise you will have undefined behavior if the input has too many characters.

Here is a modified version:

#include <stdio.h>

int getword200(char *buf) {
    return scanf("%199s", buf);
} 

int main() {
    char word[200];
    if (getword200(word) == 1)
        printf("This is the string: %s\n", word);
    return 0;
}

The above function assumes the array has a length of at least 200. It would be more general to pass the actual array length and modify the code to handle any length:

#include <limits.h>
#include <stdio.h>

int getword(char *buf, size_t size) {
    char format[32];
    int length;
    if (size == 0)
        return NULL;
    if (size == 1) {
        *buf = '\0';
        return buf;
    }
    if (size > INT_MAX)
        length = INT_MAX;
    else
        length = size - 1;
    snprintf(format, sizeof format, "%%%ds", length)
    return scanf(format, buf);
}

int main() {
    char word[200];
    if (getword(word, sizeof word) == 1)
        printf("This is the string: %s\n", word);
    return 0;
}
like image 135
chqrlie Avatar answered Dec 03 '25 12:12

chqrlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!