What is the correct way to declare a string in C?

1

There are several ways to declare a variable of type string in C as:

char *str;
char str[];
char str[100];
char str[1][100];

What I would like to know is, is there a correct way to declare a variable of type string or more recommended for certain cases?

    
asked by anonymous 11.09.2017 / 04:27

2 answers

6

None of them are declaring strings , they are declaring variables that can support strings .

The last one seems strange to me, but it works, if used right, is generally not used unless it has a specific reason. The others are all correct.

This declares that the variable str* will be a pointer to characters. Where are these characters is problem of another part of the code say, what you need is that then put the string address in this variable.

char *str;

The following is not allowed because you can not determine the size of array .

char str[];

It's already changing a bit because it already saves space for 100 characters (99 useful) and the string will be next to the variable already allocated in the stack . The content will be placed next.

char str[100];

In fact the most common is to do so in the stack or static area:

#include <stdio.h>

int main(void) {
    char str[] = "teste";
    char *strx = "teste";
    printf("%s", str);
    printf("%s", strx);
}

See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .

See more in Char pointer or char array .

Understand the difference between array and pointer .

And still read:

11.09.2017 / 05:15
0

I played around with struct to see if I could do a string implementation. I even managed to, but I do not think it works for writing to a text file. I have not tested yet.

#include <stdio.h>
#include <stdlib.h>


// Declaração do tipo string.
typedef struct STRING *string;

// Declaração de um struct usando o tipo string.
typedef struct DISCIPLINA{
    int cod;
    string nome;
}Disciplina;

int main(int argc, char *argv[]) {
    // Declarando uma variável do tipo string
    string frase;

    // Primeiro teste.
    frase = "teste de string";
    printf("%s\n", frase);

    // Segundo teste, alterando o valor da variável.
    frase = "outro teste de string";
    printf("%s\n", frase);

    // Terceito teste, fazendo uma entrada pelo teclado.
    printf("Digite algo: "); fflush(stdin); 
    frase = gets(malloc(100));
    printf("Voce digitou: %s.\n", frase);

    // Quarto teste, Fazendo a estrada na struct pelo teclado.
    Disciplina d;
    d.cod = 1;
    //d.nome = "orientacao a objetos";
    printf("Digite o nome da disciplina: "); fflush(stdin); 
    d.nome = gets(malloc(100)); 
    printf("Cod: %i Nome: %s\n", d.cod, d.nome);

    return 0;
}
    
26.11.2017 / 12:10