How to create and use string arrays in Visual C++

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.

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.


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:
Propriedades

ID do Artigo: 310809 - Última Revisão: 28 de ago de 2007 - Revisão: 1

Comentários