CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    Dec 2009
    Posts
    1

    problem getting function to change value of array element

    Newbie to C++ programming. I am trying to pass a pointer to an array element to a function and have the function change the value, but I'm getting a memory overwrite error when the program runs. The program sends a string to the function which is then suppose to change all of the letters to uppercase. Any help would be appreciated.


    Code:
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    
    using namespace std;
    using namespace System;
    
    void toUpper(char* letter, int len){
    	
    	char lower_case[] = { "abcdefghijklmnopqrstuvwxyz" };
    	char upper_case[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" };
    	int array_size = 1 * sizeof(lower_case);
    	int count = 0;
    
    		while(count < len){
    			
    			if(*letter == ' ') {
    				count++;
    				letter++;
    				continue;
    			}
    			
    			for(int i = 0; i < array_size; i++){
    
    				if(*letter == lower_case[i]) {
    					*letter = upper_case[i];
    					break;
    				}
    				else if(*letter == upper_case[i]){
    						*letter = upper_case[i];
    						break;
    				}
    			}
    		letter++;
    		count++;
    		}
    }
    	
    
    int main(array<System::String ^> ^args)
    {
    	char* stars[][80] = { "Robert Redford", "Chuck Norris", "Alec Baldwin" };
    	int count = 0;
    	int len = strlen(*stars[0]);
    	toUpper(*stars[0], len);
    	cout << *stars[0] << endl;
    }
    
    |
    Last edited by Marc G; December 15th, 2009 at 09:34 AM. Reason: added code tags

  2. #2
    Join Date
    Jun 2006
    Posts
    645

    Re: problem getting function to change value of array element

    Hi,
    If in case you want toupper() function provided by STL? Here is one of the references:
    you can find many more if only you google

    I have modified your code as under:

    Code:
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <ctype>
    
    using namespace std;
    // using namespace System;   I hope you are not using managed C++ and if so use that forum
    
    size_t getPtrSize( char *ptr )
    {   return sizeof( ptr );  }
    
    void toUpper(char* letter, int len)
    {
    	char lower_case[] = { "abcdefghijklmnopqrstuvwxyz" };
    	char upper_case[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" };
    
    	// commented out .... int array_size = 1 * sizeof(lower_case);
                    // MSDN says that when sizeof operates on char type data the result is always 1
                    // This indicates that your method reads only first char in your array
                    // Also, it seems, sizeof accepts a pointer argument and you are passing static array
                    
                    int array_size = static_cast<int>getPtrSize(lower_case)
    	int count = 0;
    	while(count < len)
                   {
    	    if(*letter == ' ')
                       {
    	       count++;
    	       letter++;
    	       continue;
    	   }
      	   for(int i = 0; i < array_size; i++)        // you can directly call getPtrSize here...
                       {
                           if(*letter == lower_case[i])
                           {
    	            *letter = upper_case[i];
    	             break;
                           }
    	       else if(*letter == upper_case[i])
                                  {
    		   *letter = upper_case[i];
    		   break;
    	              }
    	  }
    	  letter++;
    	  count++;
                }
    }
    
    // the following main you are using is for managed C++....and this is not the right forum
    // int main(array<System::String ^> ^args)
    // the main in standard C++ is as under...
    // int main(int argc, char **argv)...
    // However, you are not inputing anything from commandline
    // You are setting the string values from within the program and so u can use the following
    int main(void)
    {
    	char* stars[][80] = { "Robert Redford", "Chuck Norris", "Alec Baldwin" };
    	int count = 0;
    	int len = strlen(*stars[0]);
    	toUpper(*stars[0], len);
    	cout << *stars[0] << endl;
    }
    |
    I have just about hinted you. The code should now work barring a few compile errors. Those would not be difficult to detect.

    Regards,
    Bhushan

  3. #3
    Join Date
    Apr 2009
    Location
    Cochin
    Posts
    83

    Smile Re: problem getting function to change value of array element

    You are trying to change the value of a const char* type which is not allowed and the operation fails with a access violation error.

    You should try something like this :

    Code:
    void main(void)
    {
    
    char* myTest = (char*)malloc( sizeof("Robert Redford") );
    
    strcpy( myTest, "Robert Redford" );
    int count = 0;
    int len = strlen(myTest);
    toUpper(myTest, len);
    std::cout << myTest << endl;
    
    free( myTest);
    system("pause");
    }
    I had discarded your function part... Now it will work.

    Also do a brushup on your basics in pointer by refering a book.. good luck
    Last edited by CoolPG; December 16th, 2009 at 07:08 AM.
    "I studied everything but never topped. Today, toppers of the world's best universities are my employees"

    -William Henry Gates (Bill Gates)

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: problem getting function to change value of array element

    Quote Originally Posted by hansfordmc View Post
    Newbie to C++ programming.
    Code:
    int main(array<System::String ^> ^args)
    You are not learning "true" C++, as that line of code is not C++. It is an extension of the C++ language that Microsoft calls "Managed C++", and is not proper C++. That code isn't even relevant to this forum (there is a separate forum called Managed C++).

    Secondly, there is already a toupper() and tolower() functions in the C++ library. If you want to turn a non-const sequence of characters to upper or lower case, use std::transform().
    Code:
    #include <algorithm>
    #include <cctype>
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        string s1 = "This is a test";
        transform(s1.begin(), s1.end(), s1.begin(),  toupper);  // convert to upper case
        cout << s1;  
    }
    Third, any beginner C++ program using "strlen", "strcpy", etc. IMO is flawed. No beginner C++ program should be using these functions, instead the usage of std::string class should replace these calls.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; December 16th, 2009 at 07:30 AM.

  5. #5
    Join Date
    Apr 1999
    Posts
    27,449

    Re: problem getting function to change value of array element

    Quote Originally Posted by CoolPG View Post
    You should try something like this :

    Code:
    void main(void)
    The main() function returns int, not void.
    Code:
    char* myTest = (char*)malloc( sizeof("Robert Redford") );
    Why introduce malloc() and free()? The code below does the same thing:
    Code:
    char myTest[sizeof("Robert Redford")] = "Robert Redford";
    Regards,

    Paul McKenzie

  6. #6
    Join Date
    Apr 2009
    Location
    Cochin
    Posts
    83

    Thumbs up Re: problem getting function to change value of array element

    Thanks for pointing out mistakes, Paul

    I'm sorry i got result what the OP is asking for. I didnt know that this was a risky method.

    And, about the main() i strongly believe i had seen somewhere in a Microsoft page where they says main can return void type also.

    and, if i'm compiling a program in MSVC with void main() no compiler errors or warnings are thrown out. The standard(as per C99) suggests main should return int.

    But i'm confused with the Microsoft statement and C99 standard suggestion.

    Here is the MSDN link i had.

    http://msdn.microsoft.com/en-us/libr...wh(VS.80).aspx
    Last edited by CoolPG; December 16th, 2009 at 10:51 PM.
    "I studied everything but never topped. Today, toppers of the world's best universities are my employees"

    -William Henry Gates (Bill Gates)

  7. #7
    Join Date
    Apr 1999
    Posts
    27,449

    Re: problem getting function to change value of array element

    Quote Originally Posted by CoolPG View Post
    Thanks for pointing out mistakes, Paul

    I'm sorry i got result what the OP is asking for. I didnt know that this was a risky method.

    And, about the main() i strongly believe i had seen somewhere in a Microsoft page where they says main can return void type also.
    It doesn't matter what Microsoft says. The ANSI/ISO C++ specification states that the main() function returns an int.

    http://www.parashift.com/c++-faq-lit....html#faq-29.3

    Secondly, you aren't really "voiding" anything by making main() "void". The main() function still returns an int to the system. Look at the runtime when main() terminates -- an int is returned.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; December 16th, 2009 at 11:07 PM.

  8. #8
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: problem getting function to change value of array element

    Microsoft throws a lot of non-standard extensions into their compiler. Doesn't mean it's always a good idea to use them.

  9. #9
    Join Date
    Apr 2009
    Location
    Cochin
    Posts
    83

    Thumbs up Re: problem getting function to change value of array element

    Thanks Paul and Lindley.

    1 more doubt.

    Secondly, you aren't really "voiding" anything by making main() "void". The main() function still returns an int to the system. Look at the runtime when main() terminates -- an int is returned.
    So, if it is the case why ISO is restricting programmers from using "void" as return type for main() and is there any underlying risk in using this void type. sorry for annoying, i'm a beginner.




    PS : Dont consider this as trolling or thread hijacking. but this doubt is quite situational, and i dont believe in need of another thread for asking this.
    "I studied everything but never topped. Today, toppers of the world's best universities are my employees"

    -William Henry Gates (Bill Gates)

  10. #10
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: problem getting function to change value of array element

    Quote Originally Posted by CoolPG
    So, if it is the case why ISO is restricting programmers from using "void" as return type for main()
    Because it was chosen to standardise on int as the return type for the global main function, at least for programs in a hosted environment.

    Quote Originally Posted by CoolPG
    and is there any underlying risk in using this void type.
    In generaly, the return type depends on the function. If you are talking about the risk of using void as the return type of the global main function, then there is the risk that your otherwise perfectly portable program may fail to compile on another compiler that reasonably conforms to the C++ standard.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  11. #11
    Join Date
    Apr 2009
    Location
    Cochin
    Posts
    83

    Smile Re: problem getting function to change value of array element

    Thank you laserlight for replying and clearing the doubt.

    It was disappointing when other people went away not replying after getting their repute
    "I studied everything but never topped. Today, toppers of the world's best universities are my employees"

    -William Henry Gates (Bill Gates)

  12. #12
    Join Date
    Apr 1999
    Posts
    27,449

    Re: problem getting function to change value of array element

    Quote Originally Posted by CoolPG View Post
    So, if it is the case why ISO is restricting programmers from using "void" as return type for main() and is there any underlying risk in using this void type. sorry for annoying, i'm a beginner.
    Since C++ borrows a lot of the ISO standard from 'C', some C compilers will not flag the "void main()" as an error, but will produce unpredictable results when the program is run.

    There was a link to an article (don't remember the link now) where it was shown that for some environments "void main()" produced a crash when the program terminated due to the return not generating the correct code.

    For 'C', you can make any function return a different type than what it actually does return. Of course, doing so produces unpredictable results, and I guess "void main()" can fall into this category.

    Edit:

    Here is the link:

    http://users.aber.ac.uk/auj/voidmain.shtml

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; December 17th, 2009 at 07:41 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured