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

Asked

Viewed 8,939 times

5

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

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

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

3 answers

11


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

The last one seems strange to me, but it works, if used right, generally it is 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 these characters are is another part of the code’s problem to say, what you need is to then enter the address of string in this variable.

char *str;

The following is not allowed because it has no way to determine the size of the array.

char str[];

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

char str[100];

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

#include <stdio.h>

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

See more in Char pointer or char array?.

Understand the difference between array and pointer.

And still read:

  • I’ve seen people start a string using strcpy(), is it recommended to use it? If so, in which cases?

1

I played a little struct to see if I could do a string implementation. I did, but I don’t think it works to write to a text file. I haven’t run the test 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;
}

1

Note that declaring a char pointer, if you do not declare the contents of the string directly, may generate an error Segmentation fault (for accessing improper addresses), since no memory was allocated to store a given string. Example:

#include <stdio.h>

int main(void)
{
    char *string;
    fgets(string, 30, stdin); // Fazendo a leitura da string
    printf("%s\n", string);   // Irá apresentar um erro segmentation default
    return 0;
}

Correct way (allocating memory to store the string):

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

int main(void)
{
    char *string;
    string = malloc(30 * sizeof(char)); // Alocando 30 bytes para armazenar a string
    fgets(string, 30, stdin);           // Fazendo a leitura da string
    printf("%s\n", string);             // Imprimindo a string na tela
    free(string);                       // Liberando memória alocada
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.