Thread: strings and functions

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    13

    strings and functions

    hi i am confused about how to change a string from a function

    i try

    Code:
    int main()
    {
    	
    	char  *aString = NULL ;
    	
    	aString = " stringFirst";
    
    	changeAString(aString);
    	
    	printf("MAIN: the value of string is %s\n",aString);	
    
    ..
    }
    
    void changeAString(char * ref)
    {
    	char * temp = "bbbb\0";
    	
    	ref = temp;
    	
    	
    	printf(" changeAString : ref string in function is %s \n",ref);
    	
    	
    	
    }
    ans i get bbbb inside the function and ...
    stringFirst from main ?

    doesn't
    Code:
     ref = temp;
    mean that the char* ptr's are know pointing to the same thing, in this case bbbb

  2. #2
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    You have a number of problems there.
    1) char * str = "String First", creates a pointer to a read-only part of memory (where string literals are being held. You shouldn't ever try to change a string literal!
    2) chr * temp = "bbbb\0", that will literally add a slash and then a zero so you will have a 6 character string. String literals in double-quotes are already NULL-terminated.
    3) ref = temp doesn't do what you think it does. When your function is called, it's passes the address of the string literal that aString points to. Inside changeAStrings, the input parameter ref is given that address. Then when you do ref = temp, you change the address that ref holds, not what ref points to. Your last statement is partly right, ref and temp are both pointing to the same thing, but not aString.

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  3. #3
    Registered User
    Join Date
    Aug 2008
    Posts
    13
    thank you very much for your response and as to the first two points i have done some reading now on string literals and understand that they can't be changed ( again thankyou this is great knowledge)

    i am however still struggling with changing a string from within a function, for example if i want to change an int i go

    Code:
    int main()
    {
    	int b = 5;
    	
    	changeAnInt(&b);
    ...
    }
    
    void  changeAnInt(int * ref)
    {
    	int val = 2;
    	*ref = val;
    	
    	
    }
    an dthe value if b no in main is now 2.....

    however if i go

    Code:
    int main()
    {
    	int b = 5;
    	
    	char  *aString = NULL ;
    
    	changeAString(aString);
    
    ...
    }
    
    
    void changeAString(char *ref)
    {
    	char * temp = malloc(sizeof(char)*6);
    	
    	
    	strcpy(temp,"boo");
    
    	ref = temp;
    	
    	
    	printf(" changeAString ref string in function is %s \n",temp);
    	
    	
    	
    }
    i still can't get the aString in main to point to the string in the function ....
    what i want to be able to do is something like
    Code:
     *ref = temp
    but i get lvalue errors is there a way to do this or am i just attempting something that can't be done ??

    btw . the only success i have had so far is when i assign the memory in main so char aString[5] ..... everything else has failed ..

    thanks

  4. #4
    Registered User
    Join Date
    Aug 2008
    Posts
    15
    You cant expect to print the aString as "boo" in main & will print only inside changeAString func.

    If you want to do so then declare the variable temp in the global scope, as now it is local to changeAString func.

    One more thing,
    Strcpy should be used for char arrays, not for char pointers. Assign the value directly.
    Last edited by patil.vishwa; 09-11-2008 at 11:06 PM.

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    when you want to change var b - you pass pointer to b
    when you want change var aString - you need pass the pointer to it. The type is irrelevant here. So fix your code accordingly
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  6. #6
    Registered User
    Join Date
    Aug 2008
    Posts
    13
    thanks for all the helpful responses i have "kinda" got it ...

    i have been unsuccessful at simply getting a char pointer in main to "point to" a string that i create in some function...

    the only success i have had is when i assign memory in main, null the pointers, and then assign individual chars below...
    Code:
    int main()
    {
    	
    	int i =0;
    	char  *aString = NULL ;
    
    
    	changeAnInt(&b);
    	
    	aString = malloc(sizeof(char)*10);
    	for(i=0;i<10;i++)
    		aString[i]='\0';
    	
    	
    	changeAString(aString);
    	
    	
    	if(aString==NULL)
    	{
    		printf(" astring is still null\n");
    		
    	}
    	else
    	printf("MAIN: the value of string is %s\n",aString);	
    	
    ...}
    
    void changeAString(char *ref)
    {
    	char* temp = NULL;
    	
    	temp = malloc(sizeof(char)*10);
    		
    	temp = "boo";
    
    	ref[0]= temp[0];    // this works 
    	ref[1]= temp[1];
    	ref[2]= temp[2];
    
    	/*ref = temp;*/    // this does not work 
    	
    	
    	
    	printf(" changeAString ref string in function is %s \n",temp);
    }

    so what i am guessing is that you can't just go

    Code:
    int main()
    {
    
        char *aString = NULL;
        changeString(aString);
    
    
    }
    i understand that its not working but i don't understand why ???

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    To change something in a funciton, you need to have a pointer to it. So if you want to change the value of a char * in a function, you need to have a char ** passed in.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User
    Join Date
    Apr 2007
    Location
    Sydney, Australia
    Posts
    217
    Just do this:

    Code:
    void ChangeString(char* outStr, size_t outSize);
    int main()
    {
      char myString[0xFF] = "";
      ChangeString(myString, sizeof(myString));
      printf("&#37;s\n", myString);
      return 0;
    }
    
    void ChangeString(char* outStr, size_t outSize)
    {
      strncpy(outStr, "boo", outSize);
    }

  9. #9
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Your idea is to store in aString the string "boo" right?
    First of all, you check if aString is NULL in the wrong point. It will be NULL only if malloc failed. So you need to put the checking right under malloc. If malloc failed you cannot initialize the aString to \0.

    Now, you have two ways to do what you want.
    1) Your function can create a string with malloc, as you do with temp, and store the value "boo". You already did this. So there will be a string (temp) that has the value you want. Now, the pointer temp cannot be used outside the function, since it has local scope. So what you do in this occasions is return its value. So this will work:
    Code:
    temp changeAString(void)
    {
    	char* temp = NULL;	
    	temp = malloc(sizeof(char)*10);		
    	temp = "boo"; //not sure if this works. if not then strcpy(temp, "boo");
            printf(" changeAString ref string in function is &#37;s \n",temp);
            return temp;
    }
    // use like this
    aString = changeAString();
    //to deallocate memory
    free(aString);
    2) You can simply do this:
    EDIT: 39ster wrote something similar

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing strings to functions and modifying them
    By diddy02 in forum C Programming
    Replies: 6
    Last Post: 08-11-2008, 01:07 AM
  2. Functions and Strings Question
    By StrikeMech in forum C Programming
    Replies: 4
    Last Post: 07-18-2007, 06:07 AM
  3. passing strings from functions as the "return" part
    By fraktal in forum C Programming
    Replies: 8
    Last Post: 12-13-2005, 01:38 AM
  4. Creating Functions that use Format control Strings
    By tzuchan in forum C Programming
    Replies: 6
    Last Post: 03-29-2004, 12:50 PM
  5. Using Strings with Functions
    By DJH in forum C Programming
    Replies: 10
    Last Post: 10-19-2001, 04:40 PM