logo

Uma matriz de strings em C

Um Array é a estrutura de dados mais simples em C que armazena dados homogêneos em locais de memória contíguos. Se quisermos criar um Array, declaramos o tipo Data e fornecemos elementos a ele:

 #include int main() { int i, arr[5] = {1, 2, 4, 2, 4}; for(i = 0; i <5; i++) { printf('%d ', arr[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> 1 2 4 2 4 </pre> <p>In C, a Character and a String are separate data types, unlike other programming languages like Python. A String is a collection of Characters. Hence, to define a String, we use a Character Array:</p> <pre> #include int main() { char str[8]; printf(&apos;Enter a String: &apos;); scanf(&apos;%s&apos;, &amp;str); printf(&apos;%s&apos;, str); } </pre> <p> <strong>Output:</strong> </p> <pre> Enter a String: Hello Hello </pre> <p>Now, we want to create an Array of Strings which means we are trying to create an Array of Character Arrays. We have two ways we can do this:</p> <ol class="points"> <li>Using Two-dimensional Arrays</li> <li>Using Pointers</li> </ol> <h3>Using Two-dimensional Arrays:</h3> <p>Creating a String Array is one of the applications of two-dimensional Arrays. To get a picture of the arrangement, observe the below representation:</p> <p>For suppose we want to create an Array of 3 Strings of size 5:</p> <img src="//techcodeview.com/img/c-tutorial/46/an-array-strings-c.webp" alt="An Array of Strings in C"> <p>Every String in a String Array must terminate with a null Character. It is the property of a String in C.</p> <p> <strong>Syntax to create a 2D Array:</strong> </p> <pre> Data_type name[rows][columns] = {{values in row 1}, {values in row 2}&#x2026;}; </pre> <p> <strong>Syntax to create a String Array:</strong> </p> <pre> char Array[rows][columns] = {&apos;String1&apos;, &apos;String2&apos;...}; </pre> <p> <strong>Now, let us create an example String Array:</strong> </p> <ul> <li>Observe that when we assign the number of rows and columns, we need to consider the Null Character to the length.</li> </ul> <pre> #include int main() { int i; char Array[3][6] = {&apos;Black&apos;, &apos;Blame&apos;, &apos;Block&apos;}; printf(&apos;String Array: 
&apos;); for(i = 0; i <3; i++) { printf('%s
', array[i]); } return 0; < pre> <p> <strong>Output:</strong> </p> <pre> String Array: Black Blame Block </pre> <ul> <li>char Array[3][6] = {&apos;Black&apos;, &apos;Blame&apos;, &apos;Black&apos;} -&gt; {{&apos;B&apos;, &apos;l&apos;, &apos;a&apos;, &apos;c&apos;, &apos;k&apos;, &apos;&apos;}, {&apos;B&apos;, &apos;l&apos;, &apos;a&apos;, &apos;m&apos;, &apos;e&apos;, &apos;&apos;}, {&apos;B&apos;, &apos;l&apos;, &apos;a&apos;, &apos;c&apos;, &apos;k&apos;, &apos;&apos;}}</li> <li>We cannot directly manipulate the Strings in the Array as a String is an immutable data type. The compiler raises an error:</li> </ul> <pre> char Array[0] = &apos;Hello&apos;; </pre> <p> <strong>Output:</strong> </p> <pre> [Error] assignment to expression with Array type </pre> <ul> <li>We can use the strcpy() function to copy the value by importing the String header file:</li> </ul> <pre> char Array[3][6] = {&apos;Black&apos;, &apos;Blame&apos;, &apos;Block&apos;}; strcpy(Array[0], &apos;Hello&apos;); for(i = 0; i <3; i++) { printf('%s
', array[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> String Array: Hello Blame Block </pre> <p> <strong>The Disadvantage of using 2D Arrays:</strong> </p> <p>Suppose we want to store 4 Strings in an Array: {&apos;Java&apos;, &apos;T&apos;, &apos;point&apos;, &apos;JavaTpoint&apos;}. We will store the Strings like this:</p> <img src="//techcodeview.com/img/c-tutorial/46/an-array-strings-c-2.webp" alt="An Array of Strings in C"> <ul> <li>The number of rows will be equal to the number of Strings, but the number of columns will equal the length of the longest String.</li> <li>The memory allocated to all the Strings will be the size of the longest String, causing &apos; <strong>Memory wastage</strong> &apos;.</li> <li>The orange part in the above representation is the memory wasted.</li> </ul> <h3>Using Pointers:</h3> <p>By using Pointers, we can avoid the Disadvantage of Memory wastage. But how do we do this?</p> <p>We need to create an Array of Pointers pointing to Strings. Hence, we need to create an Array of type &apos; <strong>char*</strong> &apos;. This way, all the Strings are stored elsewhere in the exactly needed memory, and the Pointers in the Array point to those memory locations causing no memory wastage. More specifically, the Pointers in the Array point to the first Character of the Strings.</p> <p> <strong>Syntax to create an Array of Pointers:</strong> </p> <p>Data Type* name[] = {&apos;Value 1&apos;, &apos;Value 2&apos;&#x2026;};</p> <p> <strong>Syntax to create an Array of String Pointers:</strong> </p> <p>char* Array[] = {&apos;String 1&apos;, &apos;String 2&apos;&#x2026;};</p> <p> <strong>Representation:</strong> </p> <img src="//techcodeview.com/img/c-tutorial/46/an-array-strings-c-3.webp" alt="An Array of Strings in C"> <p> <strong>Now, let us create an example String Array:</strong> </p> <pre> #include #include int main() { int i; char* Array[] = {&apos;HI&apos;, &apos;UP&apos;, &apos;AT&apos;}; printf(&apos;String Array:
&apos;); for(i = 0; i <3; i++) { printf('%s
', array[i]); } return 0; < pre> <p> <strong>Output:</strong> </p> <pre> String Array: HI UP AT </pre> <h3>Summary:</h3> <p>We cannot create a String Array like a normal one, as a String is an Array of Characters. We have two ways to do this:</p> <p> <strong>1. Using a Two-Dimensional Array:</strong> </p> <p>The Disadvantage of using this way is &apos; <strong>Memory wastage</strong> ,&apos; as the memory allocated to every String in the Array will be the memory required to store the longest String of the Array.</p> <p> <strong>2. Using Pointers:</strong> </p> <p>Using Pointers, we create a single-dimensional Array of Pointers pointing to Strings. Following this method can eliminate the &apos;Memory wastage&apos; Disadvantage.</p> <hr></3;></pre></3;></pre></3;></pre></5;>

Em C, um caractere e uma string são tipos de dados separados, ao contrário de outras linguagens de programação como Python. Uma String é uma coleção de caracteres. Portanto, para definir uma String, usamos um Character Array:

 #include int main() { char str[8]; printf(&apos;Enter a String: &apos;); scanf(&apos;%s&apos;, &amp;str); printf(&apos;%s&apos;, str); } 

Saída:

 Enter a String: Hello Hello 

Agora, queremos criar um Array of Strings, o que significa que estamos tentando criar um Array of Character Arrays. Temos duas maneiras de fazer isso:

  1. Usando matrizes bidimensionais
  2. Usando ponteiros

Usando matrizes bidimensionais:

Criar um String Array é uma das aplicações de Arrays bidimensionais. Para ter uma ideia do arranjo, observe a representação abaixo:

Suponhamos que queremos criar um Array de 3 Strings de tamanho 5:

concatenação de string java
Uma matriz de strings em C

Cada String em um String Array deve terminar com um caractere nulo. É propriedade de uma String em C.

Sintaxe para criar um array 2D:

 Data_type name[rows][columns] = {{values in row 1}, {values in row 2}&#x2026;}; 

Sintaxe para criar um String Array:

 char Array[rows][columns] = {&apos;String1&apos;, &apos;String2&apos;...}; 

Agora, vamos criar um exemplo de String Array:

  • Observe que quando atribuímos o número de linhas e colunas, precisamos considerar o Caractere Nulo ao comprimento.
 #include int main() { int i; char Array[3][6] = {&apos;Black&apos;, &apos;Blame&apos;, &apos;Block&apos;}; printf(&apos;String Array: 
&apos;); for(i = 0; i <3; i++) { printf(\'%s
\', array[i]); } return 0; < pre> <p> <strong>Output:</strong> </p> <pre> String Array: Black Blame Block </pre> <ul> <li>char Array[3][6] = {&apos;Black&apos;, &apos;Blame&apos;, &apos;Black&apos;} -&gt; {{&apos;B&apos;, &apos;l&apos;, &apos;a&apos;, &apos;c&apos;, &apos;k&apos;, &apos;&apos;}, {&apos;B&apos;, &apos;l&apos;, &apos;a&apos;, &apos;m&apos;, &apos;e&apos;, &apos;&apos;}, {&apos;B&apos;, &apos;l&apos;, &apos;a&apos;, &apos;c&apos;, &apos;k&apos;, &apos;&apos;}}</li> <li>We cannot directly manipulate the Strings in the Array as a String is an immutable data type. The compiler raises an error:</li> </ul> <pre> char Array[0] = &apos;Hello&apos;; </pre> <p> <strong>Output:</strong> </p> <pre> [Error] assignment to expression with Array type </pre> <ul> <li>We can use the strcpy() function to copy the value by importing the String header file:</li> </ul> <pre> char Array[3][6] = {&apos;Black&apos;, &apos;Blame&apos;, &apos;Block&apos;}; strcpy(Array[0], &apos;Hello&apos;); for(i = 0; i <3; i++) { printf(\'%s
\', array[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> String Array: Hello Blame Block </pre> <p> <strong>The Disadvantage of using 2D Arrays:</strong> </p> <p>Suppose we want to store 4 Strings in an Array: {&apos;Java&apos;, &apos;T&apos;, &apos;point&apos;, &apos;JavaTpoint&apos;}. We will store the Strings like this:</p> <img src="//techcodeview.com/img/c-tutorial/46/an-array-strings-c-2.webp" alt="An Array of Strings in C"> <ul> <li>The number of rows will be equal to the number of Strings, but the number of columns will equal the length of the longest String.</li> <li>The memory allocated to all the Strings will be the size of the longest String, causing &apos; <strong>Memory wastage</strong> &apos;.</li> <li>The orange part in the above representation is the memory wasted.</li> </ul> <h3>Using Pointers:</h3> <p>By using Pointers, we can avoid the Disadvantage of Memory wastage. But how do we do this?</p> <p>We need to create an Array of Pointers pointing to Strings. Hence, we need to create an Array of type &apos; <strong>char*</strong> &apos;. This way, all the Strings are stored elsewhere in the exactly needed memory, and the Pointers in the Array point to those memory locations causing no memory wastage. More specifically, the Pointers in the Array point to the first Character of the Strings.</p> <p> <strong>Syntax to create an Array of Pointers:</strong> </p> <p>Data Type* name[] = {&apos;Value 1&apos;, &apos;Value 2&apos;&#x2026;};</p> <p> <strong>Syntax to create an Array of String Pointers:</strong> </p> <p>char* Array[] = {&apos;String 1&apos;, &apos;String 2&apos;&#x2026;};</p> <p> <strong>Representation:</strong> </p> <img src="//techcodeview.com/img/c-tutorial/46/an-array-strings-c-3.webp" alt="An Array of Strings in C"> <p> <strong>Now, let us create an example String Array:</strong> </p> <pre> #include #include int main() { int i; char* Array[] = {&apos;HI&apos;, &apos;UP&apos;, &apos;AT&apos;}; printf(&apos;String Array:
&apos;); for(i = 0; i <3; i++) { printf(\'%s
\', array[i]); } return 0; < pre> <p> <strong>Output:</strong> </p> <pre> String Array: HI UP AT </pre> <h3>Summary:</h3> <p>We cannot create a String Array like a normal one, as a String is an Array of Characters. We have two ways to do this:</p> <p> <strong>1. Using a Two-Dimensional Array:</strong> </p> <p>The Disadvantage of using this way is &apos; <strong>Memory wastage</strong> ,&apos; as the memory allocated to every String in the Array will be the memory required to store the longest String of the Array.</p> <p> <strong>2. Using Pointers:</strong> </p> <p>Using Pointers, we create a single-dimensional Array of Pointers pointing to Strings. Following this method can eliminate the &apos;Memory wastage&apos; Disadvantage.</p> <hr></3;></pre></3;></pre></3;>
  • char Array[3][6] = {'Preto', 'Culpa', 'Preto'} -> {{'B', 'l', 'a', 'c', 'k', '' }, {'B', 'l', 'a', 'm', 'e', ​​''}, {'B', 'l', 'a', 'c', 'k', ''}}
  • Não podemos manipular diretamente as Strings no Array, pois String é um tipo de dados imutável. O compilador gera um erro:
 char Array[0] = &apos;Hello&apos;; 

Saída:

 [Error] assignment to expression with Array type 
  • Podemos usar a função strcpy() para copiar o valor importando o arquivo de cabeçalho String:
 char Array[3][6] = {&apos;Black&apos;, &apos;Blame&apos;, &apos;Block&apos;}; strcpy(Array[0], &apos;Hello&apos;); for(i = 0; i <3; i++) { printf(\'%s
\', array[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> String Array: Hello Blame Block </pre> <p> <strong>The Disadvantage of using 2D Arrays:</strong> </p> <p>Suppose we want to store 4 Strings in an Array: {&apos;Java&apos;, &apos;T&apos;, &apos;point&apos;, &apos;JavaTpoint&apos;}. We will store the Strings like this:</p> <img src="//techcodeview.com/img/c-tutorial/46/an-array-strings-c-2.webp" alt="An Array of Strings in C"> <ul> <li>The number of rows will be equal to the number of Strings, but the number of columns will equal the length of the longest String.</li> <li>The memory allocated to all the Strings will be the size of the longest String, causing &apos; <strong>Memory wastage</strong> &apos;.</li> <li>The orange part in the above representation is the memory wasted.</li> </ul> <h3>Using Pointers:</h3> <p>By using Pointers, we can avoid the Disadvantage of Memory wastage. But how do we do this?</p> <p>We need to create an Array of Pointers pointing to Strings. Hence, we need to create an Array of type &apos; <strong>char*</strong> &apos;. This way, all the Strings are stored elsewhere in the exactly needed memory, and the Pointers in the Array point to those memory locations causing no memory wastage. More specifically, the Pointers in the Array point to the first Character of the Strings.</p> <p> <strong>Syntax to create an Array of Pointers:</strong> </p> <p>Data Type* name[] = {&apos;Value 1&apos;, &apos;Value 2&apos;&#x2026;};</p> <p> <strong>Syntax to create an Array of String Pointers:</strong> </p> <p>char* Array[] = {&apos;String 1&apos;, &apos;String 2&apos;&#x2026;};</p> <p> <strong>Representation:</strong> </p> <img src="//techcodeview.com/img/c-tutorial/46/an-array-strings-c-3.webp" alt="An Array of Strings in C"> <p> <strong>Now, let us create an example String Array:</strong> </p> <pre> #include #include int main() { int i; char* Array[] = {&apos;HI&apos;, &apos;UP&apos;, &apos;AT&apos;}; printf(&apos;String Array:
&apos;); for(i = 0; i <3; i++) { printf(\'%s
\', array[i]); } return 0; < pre> <p> <strong>Output:</strong> </p> <pre> String Array: HI UP AT </pre> <h3>Summary:</h3> <p>We cannot create a String Array like a normal one, as a String is an Array of Characters. We have two ways to do this:</p> <p> <strong>1. Using a Two-Dimensional Array:</strong> </p> <p>The Disadvantage of using this way is &apos; <strong>Memory wastage</strong> ,&apos; as the memory allocated to every String in the Array will be the memory required to store the longest String of the Array.</p> <p> <strong>2. Using Pointers:</strong> </p> <p>Using Pointers, we create a single-dimensional Array of Pointers pointing to Strings. Following this method can eliminate the &apos;Memory wastage&apos; Disadvantage.</p> <hr></3;></pre></3;>

A desvantagem de usar matrizes 2D:

Suponha que queiramos armazenar 4 Strings em um Array: {'Java', 'T', 'point', 'JavaTpoint'}. Armazenaremos as Strings assim:

matriz dinâmica java
Uma matriz de strings em C
  • O número de linhas será igual ao número de Strings, mas o número de colunas será igual ao comprimento da String mais longa.
  • A memória alocada para todas as Strings será do tamanho da String mais longa, causando ' Desperdício de memória '.
  • A parte laranja na representação acima é a memória desperdiçada.

Usando ponteiros:

Ao usar ponteiros, podemos evitar a desvantagem do desperdício de memória. Mas como fazemos isso?

Precisamos criar um Array de Ponteiros apontando para Strings. Portanto, precisamos criar um Array do tipo ' Caracteres* '. Dessa forma, todas as Strings são armazenadas em outro lugar na memória exatamente necessária, e os Ponteiros no Array apontam para esses locais de memória, sem causar desperdício de memória. Mais especificamente, os Ponteiros no Array apontam para o primeiro Caractere das Strings.

Sintaxe para criar um array de ponteiros:

Tipo de dados* nome[] = {'Valor 1', 'Valor 2'…};

Sintaxe para criar um array de ponteiros de string:

char* Matriz[] = {'String 1', 'String 2'…};

Representação:

Uma matriz de strings em C

Agora, vamos criar um exemplo de String Array:

 #include #include int main() { int i; char* Array[] = {&apos;HI&apos;, &apos;UP&apos;, &apos;AT&apos;}; printf(&apos;String Array:
&apos;); for(i = 0; i <3; i++) { printf(\'%s
\', array[i]); } return 0; < pre> <p> <strong>Output:</strong> </p> <pre> String Array: HI UP AT </pre> <h3>Summary:</h3> <p>We cannot create a String Array like a normal one, as a String is an Array of Characters. We have two ways to do this:</p> <p> <strong>1. Using a Two-Dimensional Array:</strong> </p> <p>The Disadvantage of using this way is &apos; <strong>Memory wastage</strong> ,&apos; as the memory allocated to every String in the Array will be the memory required to store the longest String of the Array.</p> <p> <strong>2. Using Pointers:</strong> </p> <p>Using Pointers, we create a single-dimensional Array of Pointers pointing to Strings. Following this method can eliminate the &apos;Memory wastage&apos; Disadvantage.</p> <hr></3;>

Resumo:

Não podemos criar um String Array como um array normal, pois um String é um Array de Caracteres. Temos duas maneiras de fazer isso:

urfi javed

1. Usando uma matriz bidimensional:

A desvantagem de usar desta forma é ' Desperdício de memória ,' já que a memória alocada para cada String no Array será a memória necessária para armazenar a String mais longa do Array.

2. Usando ponteiros:

Usando Ponteiros, criamos um Array unidimensional de Ponteiros apontando para Strings. Seguir este método pode eliminar a desvantagem do 'desperdício de memória'.