i was stuck trying to figure out how to pass a string from a function back to main for 4 hours not understunding anything from stack overflow. M8 thank you for this video rly helped me out
Strings are probably one of the most confusing subjects in C. It took me re-reading that darn chapter about 20 times before I got it. And sometimes I still forget. Great presentation from you about a simple subject in most any other language than C.
As per your other videos, this is a marvelously simple and straightforward explanation of the topic. What I would like to know is how to write a function that can be used -- say -- as an argument in a function like printf(). So, instead of doing this: char s[50]; getString(s); // populates s with "test"; printf("%s ", s); ..you could do this.. char s[50]; // populates s with "test" printf("%s ", getString(s)); ..of course, my example is specious and tortured to illustrate the point but you get the idea.
@@CodeVault ..thanks for the quick response! Actually, I found that in order to make this a "digestable" parm for a function like printf("%s ", ...), one would do this. char type[BUFFERSIZE]; printf("[%s] ", str_lookup(type, "good")); printf("[%s] ", str_lookup(type, "bad")); printf("[%s] ", str_lookup(type, "guess")); const char *str_lookup(char *str, char *search) { if (strcmp(search, "good") == 0) { strcpy(str, "This is good"); } else if (strcmp(search, "bad") == 0) { strcpy(str, "this is bad"); } else { strcpy(str, "Dunno good or bad"); }
Awesome video, I had this as the solution to my problem in mind but couldn't not explain why it worked, you have both solved and explained my problem. Love your channel and presentation style I am now subscribed and building a watch list for reference. Thnx and stay safe.
In order to avoid a buffer overflow, it might also be a good idea to also pass the array size as an argument, and then copy the string with the strncpy() function (which takes the size as an argument). This way one won't write past the end of the array, in case the string is too big.
100%, definitely if you run production-ready code, you should do this. I didn't want to go into such details as this was a video for beginners and it would make things a bit too complex
Thanks! There's yet another way: in the function you allocate a string dynamically and return a pointer on the string. Then, you can use it on the caller side but don't forget to free it when you don't need it anymore.
Yep, that's a way to do it as well. Although, a good practice is to keep the malloc call in the same block as the free call. Usually you don't want to return a pointer to dynamically allocated memory, but in certain niche cases it might be better.
The reason is the memory doesn't get changed. It's just marked as "deallocated". If that specific part of memory is not allocated (or modified) by anything, we can still technically use it. But, if it has been allocated (or modified) you would most likely get a crash. So you can sometimes get the expected result and sometimes get a crash. The problem is that it's outside of your control and it's unpredictable
i cannot find a solution to my question on stack overflow. Why is it that my %s " on a simple program will not run and i receive an error every single time and my cursor will not go to the next line, thank you, if you could please help
The issue is probably related to that string. The pointer you're sending is probably pointing to invalid memory and, when the function using it is trying to access that memory, it can't.
if the caller cannot have a realistic estimate of the size of the string that will be returned (so it can pre-allocate it), is storing it on the heap the only option?..
Yes. Allocating it on the stack gives the ability to reallocate the string in case it doesn't have enough space to store it. So that gives you more control over your memory.
So say you want to pull up csv files into data structures with arrays of substructures , or something like that, should I do the math around de sizes of everything to referencing those structures?
Yeah, if you're storing strings in those CSVs the char arrays in them should have enough space for each string. A good rule of thumb is to pick the a reasonable maximum a string of that type can be and double that.
In this example, there's no difference. You can use either one. It's a convention of mine and I like having them because people ask about it and they learn about them too ;) Here's a video on what they do btw: th-cam.com/video/decAHMKIo_A/w-d-xo.html
For some reason when I try what you did I get a compiler error "' 'FixNames' redefinition ; different basic types " also " 'FixNames' undefined; assuming extern returning int Where FixNames is my function. Do you have any idea about this problem and how I fix it ?
Hi, when I copy your code I get the error " 'void get String(char *): cannot convert argument 1 from 'char*[50]' to 'char*' " void getString(char* str) { strcpy(str, "test");
The problem is simply the way you're calling getString. getString(s); is wrong since s is an array of pointers to char (not just a pointer to char). I think you meant to define s as follows: char s[50]; // this is a simple char array
I passed a string to a function from main, performed some operations on it and stored it in another string. Now when I try to return the string, it shows warning: function returns address of local variable [-Wreturn-local-addr] and then takes the input but returns null.. Here is the program:- #include char* str_rev(char ar[]){ char rev[100]; int l=len(ar); for(int i=0;i
Well, of course, rev is local to str_rev so it'll be deallocated. After returning, rev would basically only have garbage values. You should just pass a pointer as parameter and give that to str_rev from main. char* str_rev(char ar[], char* res) and in main char result[100]; str_rev(ch, result); printf("%s", result);
If I call a function from main (like this getString() for example), can I return it to another function? BTW you are my candle in the night of C programming language thank you for all you do!
If you mean that, when you reach the "return" line in the getString function you want to return elsewhere from where you called that function (not in the main function) then no. It's not possible
@@CodeVault so the only way I can call the passing argument in a diferent function is if I declare it globally? I think that is how I will do it. Thanks again
The static keyword effectively makes the variable global (in lifetime) but still remain local (in scope). The variable will be stored in the same place as any other global variable.
is this only for C? i cant seem to get it work for C++, i included everything u did, but it gave me an underline by "test", with error "return value type does not match the function type"
i was stuck trying to figure out how to pass a string from a function back to main for 4 hours not understunding anything from stack overflow. M8 thank you for this video rly helped me out
Strings are probably one of the most confusing subjects in C. It took me re-reading that darn chapter about 20 times before I got it. And sometimes I still forget. Great presentation from you about a simple subject in most any other language than C.
As per your other videos, this is a marvelously simple and straightforward explanation of the topic. What I would like to know is how to write a function that can be used -- say -- as an argument in a function like printf(). So, instead of doing this:
char s[50];
getString(s); // populates s with "test";
printf("%s
", s);
..you could do this..
char s[50];
// populates s with "test"
printf("%s
", getString(s));
..of course, my example is specious and tortured to illustrate the point but you get the idea.
In the function getString you could simply return the parameter (as a char*) that you pass after you populated the string
@@CodeVault ..thanks for the quick response! Actually, I found that in order to make this a "digestable" parm for a function like printf("%s
", ...), one would do this.
char type[BUFFERSIZE];
printf("[%s]
", str_lookup(type, "good"));
printf("[%s]
", str_lookup(type, "bad"));
printf("[%s]
", str_lookup(type, "guess"));
const char *str_lookup(char *str, char *search)
{
if (strcmp(search, "good") == 0)
{
strcpy(str, "This is good");
}
else if (strcmp(search, "bad") == 0)
{
strcpy(str, "this is bad");
}
else
{
strcpy(str, "Dunno good or bad");
}
return str; //
Can't believe I just had to TH-cam "How to return a string from a function".
Welcome to C
I am addicted to your channel :)
Keep up the good work in C...!!
Great! You explained in simple terms a simple but so difficult to understand point. Thank you.
Awesome video, I had this as the solution to my problem in mind but couldn't not explain why it worked, you have both solved and explained my problem. Love your channel and presentation style I am now subscribed and building a watch list for reference. Thnx and stay safe.
Thank you for clearing my concept, was facing a lot of issues last night trying to return a string & string pointer
In order to avoid a buffer overflow, it might also be a good idea to also pass the array size as an argument, and then copy the string with the strncpy() function (which takes the size as an argument). This way one won't write past the end of the array, in case the string is too big.
100%, definitely if you run production-ready code, you should do this. I didn't want to go into such details as this was a video for beginners and it would make things a bit too complex
You are the best, i was trying for meny hours by myself, after your video i solved it immediately!!!!!!!!!!!!!
U R the best C instructor out there!
Thanks! There's yet another way: in the function you allocate a string dynamically and return a pointer on the string. Then, you can use it on the caller side but don't forget to free it when you don't need it anymore.
Yep, that's a way to do it as well. Although, a good practice is to keep the malloc call in the same block as the free call. Usually you don't want to return a pointer to dynamically allocated memory, but in certain niche cases it might be better.
@@CodeVault Right, it's easy to forget to free such a pointer.
Thank's a lot! This was exactly what I was looking for 😊 Very well explained.
thanks man, the only and the best explanation about this on youtube, saved me!
I hope I knew toy channel along ago, keep it up, you are doing awesome work
THANK YOU :'))) I love your explanations!
This video was amazing. The code editor font... nice and big... and the content was very useful!! Thank you
This was exactly what I needed! Thank you.
At around 6:35 if everything flushes out from the stack once it returns then how come we were getting pest.. The expected result.
The reason is the memory doesn't get changed. It's just marked as "deallocated". If that specific part of memory is not allocated (or modified) by anything, we can still technically use it. But, if it has been allocated (or modified) you would most likely get a crash.
So you can sometimes get the expected result and sometimes get a crash. The problem is that it's outside of your control and it's unpredictable
Thanks a lot man ! You cleared my confusion.
i cannot find a solution to my question on stack overflow. Why is it that my %s
" on a simple program will not run and i receive an error every single time and my cursor will not go to the next line, thank you, if you could please help
The issue is probably related to that string. The pointer you're sending is probably pointing to invalid memory and, when the function using it is trying to access that memory, it can't.
if the caller cannot have a realistic estimate of the size of the string that will be returned (so it can pre-allocate it), is storing it on the heap the only option?..
Yes. Allocating it on the stack gives the ability to reallocate the string in case it doesn't have enough space to store it. So that gives you more control over your memory.
Thank you for the always informative videos!!!
Give that man a medal!
DUUUUUUUUUUUUUUUUUUUDE..... Been struggling on this one. THANK YOUUUUU!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!I
thank you so much thanks to you i finished in 5 minutes something i was trying a whole day to figure out
is there a way to not accept string input from a keyboard using a c++ function
You mean to not accept letter characters but only everything else? Can you elaborate on this?
So say you want to pull up csv files into data structures with arrays of substructures , or something like that, should I do the math around de sizes of everything to referencing those structures?
Yeah, if you're storing strings in those CSVs the char arrays in them should have enough space for each string. A good rule of thumb is to pick the a reasonable maximum a string of that type can be and double that.
How could I do that with a 2 dimentional array ?
There is this video on the topic: code-vault.net/lesson/zgpd1zov1t:1603733527939
Any one please explain why he's using int main( int argc, char *argv[]) instead of using int main()
In this example, there's no difference.
You can use either one. It's a convention of mine and I like having them because people ask about it and they learn about them too ;)
Here's a video on what they do btw: th-cam.com/video/decAHMKIo_A/w-d-xo.html
@@CodeVault Thank you so very much..
I really appreciate it..
For some reason when I try what you did I get a compiler error
"' 'FixNames' redefinition ; different basic types " also
" 'FixNames' undefined; assuming extern returning int
Where FixNames is my function.
Do you have any idea about this problem and how I fix it ?
Can you send in the whole code? I think you're doing something wrong, I just don't know what
@@CodeVault How can I send it to you ?
Go to discord.code-vault.net and send it to me over there
Hi, when I copy your code I get the error " 'void get String(char *): cannot convert argument 1 from 'char*[50]' to 'char*' "
void getString(char* str) {
strcpy(str, "test");
}
int main(int argc, char *argv[]){
char* s[50];
getString(s);
s[0] = 'p';
printf("%s
", s);
return 0;
}
The problem is simply the way you're calling getString.
getString(s);
is wrong since s is an array of pointers to char (not just a pointer to char).
I think you meant to define s as follows:
char s[50]; // this is a simple char array
@@CodeVault thanks heaps I've been trying to solve this for days !!
you made it so easy to understand thank you
Excellent explanation! Thank you!
Thank you!!!! I was looking how to do this.
I passed a string to a function from main, performed some operations on it and stored it in another string. Now when I try to return the string, it shows warning: function returns address of local variable [-Wreturn-local-addr] and then takes the input but returns null..
Here is the program:-
#include
char* str_rev(char ar[]){
char rev[100];
int l=len(ar);
for(int i=0;i
Well, of course, rev is local to str_rev so it'll be deallocated. After returning, rev would basically only have garbage values. You should just pass a pointer as parameter and give that to str_rev from main.
char* str_rev(char ar[], char* res)
and in main
char result[100];
str_rev(ch, result);
printf("%s", result);
@@CodeVault got it! Thanks man!
Sir how can i return a string from a function while using scanf in the function to give it characters?
You can pass a pointer to char as parameter to that function and declare the string in the main function (or the place you call it from).
This is just incredible
Thank you my man thank you.
One subscriber for you
hello I need to convert string to const char* I have a string and I want it this way "....." could anyone help me plz ? I'm struggling with this
string from C++?
@@CodeVault no no from c. Ik there's a predefined function in C++ but I need it's equivalent in C plz
Ok, send in the code... I'm not sure what you mean
If I call a function from main (like this getString() for example), can I return it to another function? BTW you are my candle in the night of C programming language thank you for all you do!
If you mean that, when you reach the "return" line in the getString function you want to return elsewhere from where you called that function (not in the main function) then no. It's not possible
@@CodeVault so the only way I can call the passing argument in a diferent function is if I declare it globally? I think that is how I will do it. Thanks again
This explains a lot. Thanks!
Wow, your good at this!
Thank you very much! I subscribed
Is it okay to use a static variable inside the function? In that case, where in the memory is the value stored?
The static keyword effectively makes the variable global (in lifetime) but still remain local (in scope). The variable will be stored in the same place as any other global variable.
is this only for C? i cant seem to get it work for C++, i included everything u did, but it gave me an underline by "test", with error "return value type does not match the function type"
What's your function looking like?
@@CodeVault nvm i fixed it! thx for the help even though its an old video, didnt expect a reply
awesome explanation!
Thank you very much I really appreciate it! You help me a lot!! Thanks!💕
YOUR ARE THE BEST! THANK YOU VERY MUCH
You can return a struct string_struct { char string[SIZE] } from a function
Thanks! ! This video solve my problem
Awsome man .Thanks
I love U
Very nice 👍
Thanks. This helped
THANK YOU SO MUCH!!!!!!!!
thanks a lot!
perfect, thnx
thanks alot
title is pass string by ref instead return string
❤❤❤❤❤❤❤❤❤
4 pointer