How to create and use string arrays in Visual C++ (310809)



The information in this article applies to:

  • Microsoft Visual C++ 2005 Express Edition
  • Microsoft Visual C++ .NET (2003)
  • Microsoft Visual C++ .NET (2002)

This article was previously published under Q310809

SUMMARY

This article shows you how to use Managed C++ to create and use string arrays in Visual C++ .NET and in Visual C++ 2005. Although the example uses a two-dimensional string array, the information can also be applied to a one-dimensional string array or a multidimensional string array.

back to the top

Initializing an Array

Initialize a new instance of a two-dimensional __gc array that includes elements of a pointer to the String class:
Int32 nRows, nColumns;
nRows = 10;
nColumns = 10;   
String* myStringArray [,]= new String* [nRows,nColumns];
				
Next, fill the string array:
String* myString = S"This is a test";
myStringArray[x,y] = myString;
				
The variables x and y are placeholders for valid Int32 values or variables that specify the subscripted values of the array. The __gc array is zero-based.

back to the top

Complete Sample Code

#using <mscorlib.dll>
#include <tchar.h>

using namespace System;

int _tmain(void)
{
    Int32 nRows, nColumns;
    nRows = 10;
    nColumns = 10;
    String* myString = S"This is a test";

    String* myStringArray[,]= new String* [nRows,nColumns];
    myStringArray[0,0] = myString;

    Console::WriteLine(myStringArray[0,0]);
    return 0;
}
				
Note You must add a common language runtime support compiler option in Visual C++ 2005 to successful compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps:
  1. Click Project, and then click <ProjectName> Properties.
  2. Expand Configuration Properties, and then click General.
  3. Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) at the right of Common Language Runtime support under Project Defaults in the right pane, click Apply, and then click OK.
For more information about the common language runtime support compiler option, visit the following Microsoft Web site: back to the top

REFERENCES

Managed Extensions for C++ Specification
http://www.gotdotnet.com/team/cplusplus/articles/mcspec.doc

back to the top

Modification Type:MajorLast Reviewed:1/11/2006
Keywords:kbHOWTOmaster KB310809 kbAudDeveloper