-2

Im trying to pass a string like "Hello World" into a a function that looks at each character and prints it (as a base line function for something else) I looked up how to do so and read this post pass char array as argument and while it worked great for one word strings, I can't get it working for two word strings, what can I do to get it working?

#include <stdio.h>

void printer(char *string);

char string[11];

int main(){

  scanf("%s", string);

  printer(string);

  return 0;
}

void printer(char *words) {

  for (int i = 0; i < 51; i++) {

    printf("%c", words[i]);

  }

}


Barmar
  • 741,623
  • 53
  • 500
  • 612
Panthers27
  • 17
  • 3
  • 2
    `scanf` will stop at spaces. You can use something like `fgets`. [How to read a line from the console in C?](https://stackoverflow.com/q/314401) – 001 Sep 03 '21 at 20:52
  • 3
    Why are you looping up to 50? The string can be at most 10 characters plus a null terminator. – Barmar Sep 03 '21 at 20:55
  • you're passing the array fine. The problem is that you're only reading one word into the string in the first place. – Barmar Sep 03 '21 at 20:56
  • 2
    `scanf(" %10[^\n]", string);` may be what you want in this case - but you loop to `50` and address `string` out of bounds. Only index 0-10 are valid for `string`. – Ted Lyngmo Sep 03 '21 at 20:56
  • And why are you using a global variable; – Ed Heal Sep 03 '21 at 20:56
  • 1
    You should use `strlen(words)` to determine how much to print. – Barmar Sep 03 '21 at 20:56

1 Answers1

0
#include <stdio.h>

void printer(char * ptr);

int main()
{
        char buff[] = "hello world";

        printer(buff);

        return 0;
}

void printer(char * ptr)
{
    printf("The String is : %s",ptr);
}
sra js
  • 1
  • 1
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Jeremy Caney Sep 07 '21 at 00:29