0

How do i create a function in C?

How do I create a funtion in C Hello all. I want to create a function in C that accepts longer characters other than one letter. I wrote this one below, but I still get some "invalid declaration" response if I try to compile it. Here is the code #include<stdio.h> char string(void); { get_string(""); } int main (void) { string name = get_string("What is your name?\n"); printf("Your namr is %s."); } Thanks for your time.

26th May 2020, 12:06 PM
Ninety5
Ninety5 - avatar
6 odpowiedzi
+ 1
Ninety5 As I mentioned earlier, string is an array of character. If you want input, you can do this inside the main(): char name[20]; printf("Enter your name: "); scanf("%s", name); printf("Your name is: %s", name); This is how you do it. You can take number of characters that you want. It's upto you, like name[30] or name[40], etc. Also you can initialise a string without specifying this limit like: char name[] = "Your Name"; This will automatically take the size of characters you've assigned, but in both cases you can't exceed the limit at run time and if you want to avoid that you can use dynamic memory allocation (which is a totally different topic). But anyways, feel free to ask anything you want like if you can't understand what I did in my code above or if you like to add something with this or anything. Hope it helps you!
26th May 2020, 4:46 PM
Jaivrat Das
Jaivrat Das - avatar
+ 1
You have not provided an address to %s Try: printf("your name is %s",get_string)
26th May 2020, 12:33 PM
Saurabh Yadav
Saurabh Yadav - avatar
0
For now, coming to first line of your main(): string name = get_string("What is your name?\n"); I don't think string is a data type in C. Is it? You would need to make an array of characters for that. Also is get_string() your own function? Because I don't know any such predefined function and nor have you defined it. For rest of the things, I'm unable to understand what you're trying to do. So, if you could explain what u want to do then I can help u!
26th May 2020, 4:08 PM
Jaivrat Das
Jaivrat Das - avatar
0
Jaivrat Das thanks for the response. It is not a predefined function in C; I came across it in a course, CS50. I heard we could make our own function like that one, never knew it involved more than just writing a few lines. The char data type only outputs/collects (with scanf) a single character, so I wanted what could give me more letters and collect more letters, like full names.
26th May 2020, 4:29 PM
Ninety5
Ninety5 - avatar
0
Saurabh Yadav thanks for the response, that didn't do the job.
26th May 2020, 4:29 PM
Ninety5
Ninety5 - avatar
0
Jaivrat Das thanks bro.
27th May 2020, 9:34 AM
Ninety5
Ninety5 - avatar