Pular para o conteúdo principal
ProdutosFerramentas de desktopTASTECADVisualização de desenhosTASTEFILESGerenciamento de arquivosTASTEFTPTransferência de arquivosTASTESSHEspaço de trabalho remotoTASTEZIPCompactação e extraçãoTASTEWINMGerenciamento de arquivosFerramentas para desenvolvedoresTASTECODEAmbiente de desenvolvimento integrado para RustTASTESTUDIOAmbiente integrado de desenvolvimento e testesTASTEETLIntegração de dados (ETL)ServidoresTASTEREMOTEServidor de área de trabalho remotaTASTEGEOServidor geoespacialTASTEMAILEspaço de trabalho de e-mailInvestimentosTASTESTOCKAplicativo desktop de negociação automática de açõesComeçarDownloadsDocumentaçãoComprarTodos os produtos
Marketplace
Notícias
TecnologiaNotíciasNotícias de desenvolvimento de hojeDocumentaçãoLinguagens de programaçãoRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps e desktopTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos essenciaisAlgoritmos avançadosAlgoritmos práticos
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrineGuia da comunidade
ColaboreTransferência técnicaConstrução de siteConstrução de app de desktopPipeline de lançamento e pagamentoParceiro de vendasContato
ServiçosÁrea de trabalho remotaPacotes de instalação sob medida
TASTEDEV
Produtos

Ferramentas de desktop

TASTECADDesenhos complexos, abertos com levezaTASTEFILESSó os arquivos de que você precisa, o mais rápido possívelTASTEFTPO caminho mais organizado para seus arquivosTASTESSHEntre você e o servidor, uma conexão mais sólidaTASTEZIPCompacte mais rápido, extraia com mais segurançaTASTEWINMUm gerenciador de arquivos de dois painéis feito para o teclado

Ferramentas para desenvolvedores

TASTECODEEdite, compile, depure e teste apps Rust em uma única janelaTASTESTUDIODa edição aos testes remotos e às correções com IA aprovadasTASTEETLMova dados de olho nos valores

Servidores

TASTEREMOTEUma área de trabalho remota rodando no seu próprio servidorTASTEGEOUm servidor geoespacial compatível com o GeoServer, reconstruído em RustTASTEMAILRetome o controle do seu e-mail

Investimentos

TASTESTOCKNegociação automática de ações pelas regras que você define: quando e o quê

Começar

DownloadsVersões mais recentes de cada produtoDocsComo usar cada produtoComprarAssinaturas e licenças perpétuasTodos os produtosTodos os produtos de relance
Todos os produtos
MarketplaceNotícias
Tecnologia

Notícias

Notícias de desenvolvimento de hojeAnúncios oficiais de linguagens, frameworks, GitHub e IADocumentaçãoGuias de linguagens, frameworks e algoritmos

Linguagens de programação

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps e desktopTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálise de complexidade · Ordenação · Busca · Estruturas de dados básicas · Árvores e heapsAlgoritmos essenciaisBusca em grafos · Caminho mínimo e árvore geradora mínima · Programação dinâmica · Algoritmos gulosos · Divisão e conquista · BacktrackingAlgoritmos avançadosAlgoritmos de strings · Matemática e teoria dos números · Manipulação de bits · Árvores de segmentos · Union-FindAlgoritmos práticosEstratégia para entrevistas de código · Cache LRU · Limitação de taxa · Hashing consistente
Toda a documentação de desenvolvimento
Comunidade
ProjetosDescubra criadores e trabalhosRegistros de desenvolvimentoDecisões e aprendizadosPromptsInstruções reutilizáveisProblemas de ferramentas de IAProblemas e contornos de Claude, Codex, GeminiVitrineResultados concluídosGuia da comunidadeComo construímos em aberto
Colabore
Transferência técnicaApps nativos em Rust e eguiConstrução de site10 idiomas, contas, documentação e downloadsConstrução de app de desktopRust e egui, sem WebViewPipeline de lançamento e pagamentoAssinatura, MSI, deb, rpm, AppImage, hashesParceiro de vendasRecomende e ganhe 30%ContatoDesenvolvimento, parcerias e investimento
Serviços
Área de trabalho remotaAcesse seu computador pelo navegadorPacotes de instalação sob medidaSó o necessário, configurações pré-carregadas
Comprar
PT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Entrar
Entrar
TASTEDEV

De pequenas ferramentas a um desenvolvimento melhor.

support@tastedev.netApoiar TASTEDEV
ProdutosLinha de produtosComprarDocsDownloadsMarketplaceSuporte
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrine
PolíticasSobre nósPolítica de privacidadeTermos de usoTermos de assinaturaReembolsoDiretrizes da comunidade
ContaEntrarCriar conta
Visitantes
Hoje
Ontem
Visualizações totais
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro comercial
853-44-00368
Endereço
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsável pela privacidade
CHOI YOUNG GU

© 2026 TASTEDEVAs informações dos produtos se baseiam em fontes de desenvolvimento verificadas.Lançado · em melhoria

Documentação de C
C
Getting StartedSyntax BasicsTypes and DataModules and LibrariesErrors and TestingKey Concepts: Pointers and Memory
Discussões

Guia de C · 3/6

Types and Data

Por enquanto, este capítulo está disponível apenas em inglês.

In C, a type decides how many bytes a value occupies and how those bytes are interpreted. This chapter walks through integer and floating-point types, arrays, strings as character arrays, and the tools for grouping data: structs, unions, enums, and typedef.

Integer and floating-point types

The standard does not fix the exact size of integer types; it only guarantees minimum widths. Real sizes depend on the platform.

TypeGuaranteed minimum64-bit Linux and macOS64-bit Windows
char8 bits8 bits8 bits
short16 bits16 bits16 bits
int16 bits32 bits32 bits
long32 bits64 bits32 bits
long long64 bits64 bits64 bits

The long column is the one that bites people when code moves between systems. When you need an exact width, use the fixed-width types from <stdint.h> such as int8_t, int32_t, and uint64_t. For object sizes and array indexes, use size_t from <stddef.h>, which is unsigned.

Unsigned integers wrap around modulo their range, which is well defined. Signed integer overflow, on the other hand, is undefined behavior. For floating point you have float, double, and long double; double is the usual default.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <limits.h>

int main(void) {
    printf("int: %zu bytes, max %d\n", sizeof(int), INT_MAX);
    printf("long: %zu bytes\n", sizeof(long));

    uint8_t small = 255;
    small++;                      /* unsigned values wrap to 0 */
    printf("small = %u\n", (unsigned)small);

    int64_t big = INT64_C(9000000000);
    printf("big = %" PRId64 "\n", big);   /* format macro for fixed-width types */

    double avg = 10 / 4;          /* 2.0: integer division happens first */
    double ok = 10 / 4.0;         /* 2.5 */
    printf("%.1f %.1f\n", avg, ok);
    return 0;
}

Arrays

An array is a fixed number of same-typed elements laid out contiguously. Its size is set at declaration and never changes. If you provide fewer initializers than elements, the rest are zero.

int scores[5] = {90, 85, 77};               /* last two elements are 0 */
size_t n = sizeof scores / sizeof scores[0];  /* element count: 5 */

for (size_t i = 0; i < n; i++) {
    printf("%zu: %d\n", i, scores[i]);
}

int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};    /* two-dimensional array */
printf("%d\n", grid[1][2]);                 /* 6 */
Dúvidas sobre este capítulo?
Capítulo anteriorSyntax BasicsPróximo capítuloModules and Libraries

C does no bounds checking. Reading scores[5] compiles and may even appear to work, but it is undefined behavior. Also, when you pass an array to a function it decays into a pointer to its first element, so sizeof inside the function no longer gives you the element count. The convention is to pass the length alongside the array.

Strings are char arrays

There is no dedicated string type. A string is a char array terminated by a null character, '\0'. The literal "hi" takes three bytes: h, i, and the terminator.

#include <stdio.h>
#include <string.h>

int main(void) {
    char name[16] = "Kim";          /* a writable array */
    const char *lang = "C";         /* a string literal: never modify it */

    printf("%zu\n", strlen(name));  /* 3: the terminator is not counted */
    printf("%zu\n", sizeof name);   /* 16: the whole array */

    char buf[32];
    snprintf(buf, sizeof buf, "%s loves %s", name, lang);  /* never writes past buf */
    puts(buf);

    if (strcmp(name, "Kim") == 0) { /* compare contents with strcmp, not == */
        puts("same string");
    }
    return 0;
}

strcpy and strcat never check the destination size, which makes overflows easy. Reaching for snprintf, which takes the buffer size, is a safer habit. Comparing strings with == compares addresses rather than contents, so use strcmp.

Structs, unions, enums, and typedef

A struct groups values of different types. Access members with ., or with -> through a pointer. C99 designated initializers (.x = 1) let you initialize members by name, in any order.

An enum defines a set of named integer constants. A union overlays all its members on the same storage, so it holds only one of them at a time; it is normally paired with a tag that records which member is active. typedef gives a type a new name.

#include <stdio.h>

typedef enum { SHAPE_CIRCLE, SHAPE_RECT } ShapeKind;

typedef struct {
    double x, y;
} Point;

typedef struct {
    ShapeKind kind;            /* tag: which union member is valid */
    Point origin;
    union {
        double radius;                  /* SHAPE_CIRCLE */
        struct { double w, h; } size;   /* SHAPE_RECT */
    } u;
} Shape;

double area(const Shape *s) {
    switch (s->kind) {
    case SHAPE_CIRCLE: return 3.14159265 * s->u.radius * s->u.radius;
    case SHAPE_RECT:   return s->u.size.w * s->u.size.h;
    }
    return 0.0;
}

int main(void) {
    Shape c = { .kind = SHAPE_CIRCLE, .origin = { .x = 0, .y = 0 }, .u.radius = 2.0 };
    Shape r = { .kind = SHAPE_RECT, .u.size = { .w = 3.0, .h = 4.0 } };
    printf("%.2f %.2f\n", area(&c), area(&r));
    printf("sizeof(Shape) = %zu\n", sizeof(Shape));
    return 0;
}

Passing a struct by value copies the whole thing, so pass large structs by pointer and add const when the function only reads. A struct can be larger than the sum of its members because the compiler inserts padding for alignment.

Summary

  • Integer sizes vary by platform; use <stdint.h> for exact widths and size_t for sizes and indexes.
  • Signed overflow is undefined behavior; unsigned arithmetic wraps.
  • Arrays have no bounds checks and decay to pointers when passed, so pass the length too.
  • Strings are '\0'-terminated char arrays; handle them with snprintf and strcmp.
  • Group data with structs, use tagged unions, name constants with enum, and shorten type names with typedef.

0 comentários

Principais comentáriosMais recentes primeiro

Fazer login · Faça login para deixar um comentário.