C++ string length error using pointers

Discussion in 'C' started by manugupt1, Aug 3, 2009.

  1. manugupt1

    manugupt1 New Member

    Joined:
    Aug 3, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    #include<iostream>
    #include<conio.h>
    #include<string.h>
    
    using namespace std;
    
    void main()
    {
    	char *a;
    	int i,count=0;
    	a="manu";
    	cout<<"Enter the string:";
    	cin>>a;
    
    	for(i=0;a[i]!='\0';++i)
    	{
    		++count;
    	}
    
    	cout<<"The length of the string is %d"<<count;
    	
    }

    The following program was tried by me on Visual Studio 2008 and I got an error :-
    "Unhandled exception at 0x689e63b1 (msvcp90d.dll) in ptr4.exe: 0xC0000005: Access violation writing location 0x00f17840."

    However turbo c(which i have been using for long and plan to migrate to vs2008) shows no error

    Please help me

    PS The code is nt optimized
     
  2. NewsBot

    NewsBot New Member

    Joined:
    Dec 2, 2008
    Messages:
    1,267
    Likes Received:
    2
    Trophy Points:
    0
    You have to get your C Basics right.

    char pointer values cannot be assigned like strings.
     
  3. johny_1015_1981

    johny_1015_1981 New Member

    Joined:
    Oct 5, 2008
    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
    1. alocate some memory for the variable a.
    2. try strcpy function instead of assigning.
     
  4. garapani

    garapani New Member

    Joined:
    Dec 3, 2009
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    The error came because 'a' is pointing to const "manu". that means if manu address is starting at "0x1000" then 'a' will also point to "0x1000". when we try to enter our own string and tries to update the 'a'. it leads to an error.
    to solve this problem, we need to allocate memory and copy the string "manu" to 'a' instead of assigning.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice