String problem in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kujahleague
    New Member
    • Jul 2006
    • 11

    #1

    String problem in C

    Dear all
    I'm new here and also new to C language. I have been stuck with string problem in C for some time and I decide to post here to get some help, please kindly explain what I get wrong with the code

    char *ptr, *old2, *oldstring);

    printf("\nEnter oldstring expression :");
    gets(oldstring) ;
    printf("\n%s : old2", old2);
    ptr = strcpy(old2, oldstring);
    printf("\n%s : old2", ptr);
    printf("\n%s : old2", old2);

    Seems like when I entered oldstring, the program tends to freeze, I assume the problem is "segmentati on error" but I'm not sure.. Please anyone tell me how to copy the value of string to another string, I have used

    a = oldstring;

    provided a and oldstring is char*
    a value tend to change even after that I change value of oldstring.. I think it's because a is just a pointer isn't it?

    Thank you very much for all answers
  • Ashish_CPP
    New Member
    • Jul 2006
    • 35

    #2
    Hi,
    I couldn't understand your question but I think the problem with your code is that you have not initialised the pointers (oldstring, old2, etc) and without initialising them you cannot assign values to them.
    So assign addresses of variables as : oldstring = &x;
    Check this out if it solves your problem or not.

    Comment

    • jithendra
      New Member
      • Jul 2006
      • 2

      #3
      Here is a simple program to copy the contents of one string to another.
      main()
      {
      char src[10]; //source string
      char tar[10]; //target string means the string which is going to contain result
      char * ptr1;
      char *ptr2;
      printf("Enter the source string\n");
      gets(src);
      ptr1 = src; //ptr1 contains the base address of source string
      ptr2 = tar; // ptr2 contains the base address of target string
      while( *ptr1 != '\0')
      *ptr2++ = * ptr1++;
      printf("The target string is %s", tar);
      }
      This is one of the simplest way to copy the contents of 1 string to other.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Actually one of the simplest ways of copying 1 string to another is strcpy

        Code:
           char string1[10] = "Hello";
           char string2[10];
        
           strcpy(string2, string1);
        Ashish_CPP is on the right lines, you have used pointers but you have used them without pointing them at anything, a pointer has to be allocated data before you can assign any values to it.

        Code:
           char string1[10] = "Hello";
           char *string2;
        
           string2 = malloc(strlen(string1)+1);
        
           if (string2 != NULL)
           {
              strcpy(string2, string1);
           }
        If you copy pointers then they will both point to the same data so modifying the data 1 points at will affect them data the other points at (as it is the same data).

        Code:
           char string1[10] = "Hello";
           char *string2;
           char *string3;
        
           string2 = malloc(strlen(string1)+1);
        
           if (string2 != NULL)
           {
              strcpy(string2, string1);
           }
        
           string3 = string2;
        
           string3[0] = '\'';
        
           printf( "%s\n", string2 );
        this outputs

        'ello



        NOTE: If you do use malloc then you should free the data when finished

        Comment

        • kujahleague
          New Member
          • Jul 2006
          • 11

          #5
          Thank you very much, I'll see if that helps

          Comment

          • srinath_f_o_john
            New Member
            • Jul 2006
            • 2

            #6
            Sometime if you not allocate memory for these strings you may got troble SO allocate memory properly And delete properly

            Comment

            • kujahleague
              New Member
              • Jul 2006
              • 11

              #7
              Dear all,
              I've tried to allocate memory and I still got problem, could u please look at my program in the following post

              It's been giving error "Segmentati on Error" message, I really don't know what is going wrong

              Thank you

              Comment

              • kujahleague
                New Member
                • Jul 2006
                • 11

                #8
                Code:
                //This procedure take in normal string and convert to single character rep
                //such as "(img1.tga over img2.tga) in img.tga" -> "(aOb)Ic"
                //And store image filename in string variables
                
                #include <stdio.h>
                #include <stdlib.h>
                #include <string.h>
                
                int oldtonew(char *oldstring,char *newstring){
                    int i,j,k,l,count,size;
                    char *tempstring, *O, *I, *U, *A, *X, *a, *b, *c;
                    char *img[2];
                    count=0;
                    i=0;
                    j=0;
                    k=0;
                    l=0;
                	
                    size=strlen(oldstring);
                
                    while (i<size){
                	if ((oldstring[i]=='(')||(oldstring[i]==')')){
                		newstring[k]=oldstring[i];
                		k++;
                		i++;
                		}
                	else if (oldstring[i]==' '){
                		i++;
                		}
                	else{
                		j=0;
                		while ((oldstring[i]!=' ')&&(oldstring[i]!=')')
                		&&(oldstring[i]!='(')&&(i<=size)){
                			tempstring[j]=oldstring[i];
                			j++;
                			i++;
                		}
                				
                		tempstring[j]='\0';
                		printf("tempstring=::%s::\n",tempstring);
                		if (strcmp(tempstring,"over")==0) 
                			{
                			O = "over";
                			newstring[k]='O';
                			k++;
                			}
                		else if (strcmp(tempstring,"in")==0){
                			I = "in";
                			newstring[k]='I';
                			k++;
                			}
                		else if (strcmp(tempstring,"out")==0){
                			U = "out";
                			newstring[k]='U';
                			k++;
                			}  
                		else if (strcmp(tempstring,"atop")==0){
                			A = "atop";
                			newstring[k]='A';
                			k++;
                			}      
                		else if (strcmp(tempstring,"xor")==0){
                			X = "xor";
                			newstring[k]='X';
                			k++;
                			}
                		else
                            { 
                			printf("\ndebug5");
                            img[l] = malloc((strlen(tempstring))+1);
                                    
                            if (img[l] != NULL)
                			   {
                			   strcpy(img[l],tempstring);
                               
                               newstring[k]=l;
                               }
                		    img[l][strlen(img[l])]='\0';
                            l++;
                            k++;
                            }
                      } 
                    }
                    //img[0][strlen(img[0])]='\0';
                    //img[1][strlen(img[1])]='\0';
                    //img[2][strlen(img[2])]='\0';
                    //printf("string img[0] = ::%s::\n", img[0]);
                    //printf("string img[1] = ::%s::\n", img[1]);
                    //printf("string img[2] = ::%s::\n", img[2]);
                    newstring[k]='\0';
                }
                
                int main() 
                {
                	
                    char *oldstring;
                    char newstring[200];
                    char *old2, *ptr;
                    int size;
                    printf("\nEnter oldstring expression :");
                    gets(oldstring);
                    printf("\n%s : oldstring", oldstring);
                    oldtonew(oldstring,newstring);
                    printf("\nnewstring: ::%s::\n",newstring);
                    printf("\ndebug");
                    system("PAUSE");	
                    return 0;
                }

                Comment

                • Banfa
                  Recognized Expert Expert
                  • Feb 2006
                  • 9067

                  #9
                  Code:
                  //This procedure take in normal string and convert to single character rep
                  //such as "(img1.tga over img2.tga) in img.tga" -> "(aOb)Ic"
                  //And store image filename in string variables
                  
                  #include <stdio.h>
                  #include <stdlib.h>
                  #include <string.h>
                  
                  int oldtonew(char *oldstring,char *newstring){
                  
                      <snipped>
                  }
                  
                  int main() 
                  {
                  	
                      char *oldstring;
                      char newstring[200];
                      char *old2, *ptr;
                      int size;
                      printf("\nEnter oldstring expression :");
                      gets(oldstring);
                      printf("\n%s : oldstring", oldstring);
                      oldtonew(oldstring,newstring);
                      printf("\nnewstring: ::%s::\n",newstring);
                      printf("\ndebug");
                      system("PAUSE");	
                      return 0;
                  }
                  ignoring any errors that might exist in oldtonew in main you are still using the variable oldstring which is a char * which supplying any memory for it. Also rather than gets use fgets, this allows you to protect your program from buffer overrun (where you write more data to the buffer than it has storage for.

                  If I were you I would try

                  Code:
                  #include <stdio.h>
                  #include <stdlib.h>
                  #include <string.h>
                  
                  int main(int argc, char**argv) 
                  {
                  	
                      char oldstring[200];
                  
                      <snipped>
                  
                      fgets(oldstring, sizeof oldstring, stdin);
                  
                      <snipped>
                  
                      return 0;
                  }

                  Comment

                  Working...