473,469 Members | 1,573 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Why does this code snippet not work in C ?

24 New Member
It says "str" is not initialized.

Expand|Select|Wrap|Line Numbers
  1. void SInit(char *s) {
  2.    s = malloc(sizeof(char)*25);
  3. }
  4.  
  5. void SFree(char *s) {
  6.    free(s);
  7. }
  8.  
  9. int main()
  10. {
  11.    char *str;
  12.    SInit(str);
  13.    strcpy(str, "Hello, World");
  14.    printf("%d", strlen(str));
  15.    SFree(str);
  16.    getch();
  17.    return 0;
  18. }
Aug 17 '09 #1
16 2218
JosAH
11,448 Recognized Expert MVP
C (and C++) pass parameters by value, C can't even pass by reference (C++ can).

kind regards,

Jos
Aug 17 '09 #2
DelphiCoder
24 New Member
But I'm passing an address. You can do that in C. For example, this works:
Expand|Select|Wrap|Line Numbers
  1. void Init(int *n) {
  2.    *n = 5;
  3. }
  4.  
  5. int main()
  6. {
  7.    int *i;
  8.    i = malloc(sizeof(int));
  9.    Init(i);
  10.    printf("%d", *i);
  11.    getch();
  12.    return 0;
  13. }
Aug 17 '09 #3
JosAH
11,448 Recognized Expert MVP
@DelphiCoder
You are passing an address here; that function manipulates the object pointed to by that address. That is entiry different from your first example. Think of it: C passes parameters by value; that explains it all.

kind regards,

Jos
Aug 17 '09 #4
DelphiCoder
24 New Member
I'm passing an address in the first post too. I understand that C parameters by value.

Let me put it this way: Can you fix the code in the first post so that it works as intended? Maybe then I will understand what you're trying to tell me.
Aug 17 '09 #5
JosAH
11,448 Recognized Expert MVP
@DelphiCoder
Sure, here goes:

Expand|Select|Wrap|Line Numbers
  1. void SInit(char **s) { 
  2.    *s = malloc(sizeof(char)*25); 
  3.  
  4. void SFree(char *s) { 
  5.    free(s); 
  6.  
  7. int main() 
  8.    char *str; 
  9.    SInit(&str); 
  10.    strcpy(str, "Hello, World"); 
  11.    printf("%d", strlen(str)); 
  12.    SFree(str); 
  13.    getch(); 
  14.    return 0; 
  15.  
kind regards,

Jos

ps. I would've made the SInit function return the address of the allocated memory.
Aug 17 '09 #6
weaknessforcats
9,208 Recognized Expert Moderator Expert
What JosAH is saying is that in order to pass a function argument by value, the compiler needs to make a copy of the variable in order to be sure the function does not change the variable used as the argument.

Your first example shows malloc() changing the value of s. This is a copy of the variable used to make the call. In order for the function to change the value of the variable used on the call, you need to pass the address for that variable. That is, pass the address of the pointer.
Aug 17 '09 #7
DelphiCoder
24 New Member
I guess there is a gap in my understanding that I wasn't aware of. I don't see why I need to pass a pointer to a pointer.

For instance, given what you guys said, I don't understand why this code works. I'm changing the value inside the function and I don't need a pointer to a pointer to do it. There seems to be something about the "malloc" function that requires a pointer to a pointer, rather than just a pointer. "strcpy", on the other hand, operates on a pointer and the change it makes is done to the original variable, not a copy of it...

Expand|Select|Wrap|Line Numbers
  1. void Init(char *s) {
  2.    strcpy(s, "Hello");
  3. }
  4.  
  5. int main()
  6. {
  7.    char *s;
  8.    s = malloc(6 * sizeof(char));
  9.    Init(s);
  10.    printf("%s", s);
  11.    getch();
  12.    return 0;
  13. }
Aug 17 '09 #8
weaknessforcats
9,208 Recognized Expert Moderator Expert
void SInit(char *s) {
s = malloc(sizeof(char)*25);
}
This was the example.

Here the variable s is changed by the return from malloc().

Then s is destroyed when the function completes.

In order to chane the variable in main(), you need to have the address of that variable. That is, the address of s:

Expand|Select|Wrap|Line Numbers
  1. void SInit(char **s) { 
  2.    *s = malloc(sizeof(char)*25); 
Your example using strcpy is exactly the same. That is, to change the character in main(), you need the address of that character. It's the same with a pointer: To change the value of a pointer in main() you need the address of that pointer in your function.
Aug 17 '09 #9
DelphiCoder
24 New Member
Thanks a lot. I think I understand now. In most cases, we change the content of the memory block by passing a pointer to it into the function. But what I was trying to do here is change the actual pointer by making it point at a different block of memory, and to do that I have to pass a pointer to that pointer.

Thanks for the explanation.
Aug 17 '09 #10
weaknessforcats
9,208 Recognized Expert Moderator Expert
I think I understand now. In most cases, we change the content of the memory block by passing a pointer to it into the function. But what I was trying to do here is change the actual pointer by making it point at a different block of memory, and to do that I have to pass a pointer to that pointer.
You do understand that these two cases are identical? Yes?

That is, to change the value at a memory location, you need the address of that location.
Aug 18 '09 #11
Markus
6,050 Recognized Expert Expert
@DelphiCoder
*brain fart*

Mark (apologises for being off-topic).
Aug 18 '09 #12
DelphiCoder
24 New Member
@weaknessforcats
... and to change the value of the address itself, I need the address of the address.
Aug 18 '09 #13
JosAH
11,448 Recognized Expert MVP
@DelphiCoder
Yep, you got it; it is similar to Dephi/Pascal: all the 'var' parameters are passed by reference, the others are passed by value; C can only do the latter.

kind regards,

Jos
Aug 18 '09 #14
DelphiCoder
24 New Member
OK, I copied/pasted the code into my VC++ and it doesn't work. I get a 6 digit number instead of the expected string:

Expand|Select|Wrap|Line Numbers
  1. void SInit(char **s) { 
  2.    *s = malloc(sizeof(char)*25); 
  3.  
  4.  
  5. int main() 
  6.    char *str; 
  7.    SInit(&str); 
  8.    strcpy(str, "Hello, World"); 
  9.    printf("%d", str); 
  10.    free(str); 
  11.    getch(); 
  12.    return 0; 
Aug 19 '09 #15
sridhard2406
52 New Member
please change the 11 th line as

printf("%s\n",str );
Aug 19 '09 #16
DelphiCoder
24 New Member
@sridhard2406
Well duh. I do apologize. I actually spent a half hour struggling with it, never noticing the stupid mistake.
Aug 19 '09 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Gensek | last post by:
(I don't know how to make the title more specific in a useful way, sorry.) http://www.geocities.com/fusionary_2000/PingGUI.zip Requires wxPython. The part that fails is the function...
14
by: jagguy | last post by:
this works char *p ; p="xat"; cout << p <<endl;
15
by: iwdu15 | last post by:
hi, i have these 2 code snippets: Public Sub ImRec(ByVal IM As IAccIm, ByVal Sender As IAccUser) Dim str As String = IM.GetConvertedText(DECODE) Dim temp As String = str temp =...
89
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be...
4
by: Aquosus | last post by:
My Images are too large, so I will cut them way down What is wrong with my code snippet+++++++ var myImgs=document.getElementsByName("escoImg"); var numImgs=myImgs.length;
8
by: Robert Dufour | last post by:
Dim message As New MailMessage("mymail@mydomain.com", "mymail@mydomain.com", "Test", "Test") Dim emailClient As New SmtpClient("localhost") emailClient.Send(message) The IIS server is...
6
by: Marc | last post by:
The below snippet does not work...anyone know how to reference the procedure 'DrawCross()'? Private Sub MarkVORToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As...
14
by: webEater | last post by:
I have a problem, it's not browser specific, and I don't get a solution. I have an (X)HTML document, I show you a part of it: .... <!--<div class="pad">--> <div id="eventImages"><img src=""...
13
by: frk.won | last post by:
I am interested in learning how to use the VS 2005 code snippets. However, I wish to know what are the best ways to source control the code snippets? Are there any source safe/subversion...
4
by: tshad | last post by:
I was watching a video that used a code snippet to create a property and when you type "prop" tab tab, it would create the private variable as well as the property definitions with the private...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.