domingo, 31 de março de 2019

C++ builder - operador sizeof e função strlen

Quando precisamos saber o tamanho de variáveis ou de tipos,
utilizamos o operador sizeof que tem a seguinte sintaxe:
sizeof ( nome_da_variável ou_nome_do_tipo );
O que ele faz é retornar o tamanho do tipo ou da variável em bytes.
É muito importante usá-lo para que a portabilidade seja atingida
sem que tenha desperdícios de memória alocadas.
Parece estranho dizer que sizeof seja um operador,
mas se levarmos em conta que ele atua em tempo de execução
sendo trocado pelo tamanho da variável ou do tipo,
ficamos convencido de sua atuação.
A função strlen, cuja sintaxe é: strlen ( string );
mostra em seu retorno o comprimento da string,
mas fica em nossas mãos o cuidado com o terminador nulo
no final da string, já que strlen não o inclui no comprimento.
Uma string em C, é um vetor de string, 
então basta acrescentar um a mais no valor inteiro retornado por strlen.
Aqui temos um bom exemplo de uso do operador sizeof e strlen.

Veja abaixo uma imagem do programa em execução:



Veja abaixo o código do programa:


//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
bool x = false;
//---------------------------------------------------------------------------
#define SIZE 180
struct inf {
    char nomes [ 40 ];
    char *name ;
};
//---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
   Canvas -> Font -> Style = TFontStyles() << fsBold << fsUnderline
                       << fsItalic ;
    Canvas -> Font -> Color = clBlack;
    Canvas -> TextOut ( 200, 210, "Por: " );
    Canvas -> Font -> Color = clRed;
    Canvas -> TextOut ( 240, 210, "Samuel Lima" );
    Canvas -> Font -> Color = clBlack;
    Canvas -> TextOut ( 200, 230, "sa_sp10@hotmail.com" );
    Canvas -> Font -> Name = "Garamond";
    Canvas -> Font -> Size = 20;
    Canvas -> Font -> Color = clSkyBlue;
    Canvas -> TextOut ( 196, 256, "MUITO OBRIGADO" );
    SetBkMode ( Canvas -> Handle, TRANSPARENT );
    Canvas -> Font -> Color = clBlue;
    Canvas -> TextOut ( 190, 250, "MUITO OBRIGADO" );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Inf_tam ( TObject *Sender ) {
    Canvas -> Font -> Style = TFontStyles ( ) << fsItalic;
    Canvas -> Font -> Size = 14;
    Canvas -> Font -> Name = "arial";
    inf *pt;
    int i = 0, j = 0,  t = 0;
    //abaixo alocando memória para a struct
    pt = ( inf* ) malloc ( SIZE *sizeof ( inf ) );
    //abaixo alocando memória para o ponteiro name
    if ( ( pt -> name = ( char* ) malloc ( SIZE ) ) == NULL ) {
      //Criando um Label na mão
    TLabel* Label1 = new TLabel ( Form1 );
    Label1 -> Parent = Form1;
    Label1 -> Left = 75;
    Label1 -> Top = 32;
    Label1 -> Caption = "Não foi possível alocar memória para name";
    Beep ( 1000, 500 );
    exit ( 1 );
    }
    Canvas -> Font -> Size = 11;
    pt -> name = "Linguagem C";
    Canvas -> Font -> Color = clBlue;
    Canvas -> TextOut ( 120, 35, "Valor do ponteiro name" );
    Canvas -> Font -> Color = clRed;
    Canvas -> TextOut ( 372, 35, AnsiString ( pt -> name ) );
    for ( i = 0; i <  strlen ( pt -> name ); i++ ) {
        if ( pt -> name [ i ] == ' ' )
            t++;
    }
    j = strlen ( pt -> name ) - t;
    Canvas -> Font -> Color = clBlue;
    Canvas -> TextOut ( 120, 55, "Total de caracteres de name" );
    Canvas -> Font -> Color = clRed;
    Canvas -> TextOut ( 450, 55, AnsiString ( j ) );
    Canvas -> Font -> Color = clBlue;
    Canvas -> TextOut ( 120, 75, "Tamanho do ponteiro name" );
    Canvas -> Font -> Color = clRed;
    Canvas -> TextOut ( 450, 75, AnsiString ( sizeof ( pt -> name ) ) );
    Canvas -> Font -> Color = clBlue;
    Canvas -> TextOut ( 120, 95, "Tamanho da alocação estática para nomes" );
    Canvas -> Font -> Color = clRed;
    Canvas -> TextOut ( 450, 95, AnsiString ( sizeof ( pt -> nomes ) ) );
    Canvas -> Font -> Color = clBlue;
    Canvas -> TextOut ( 120, 115, "Tamanho total consumido pela struct" );
    Canvas -> Font -> Color = clRed;
    Canvas -> TextOut ( 450, 115, AnsiString ( sizeof ( *pt ) ) );
    strcpy ( pt -> nomes,"Devemos estudar linguagem de programação");
    Canvas -> Font -> Color = clBlue;
    Canvas -> TextOut ( 120, 135, "Valor da variável nomes:" );
    Canvas -> Font -> Color = clRed;
    Canvas -> TextOut ( 120, 155, AnsiString ( pt -> nomes ) );
    t = 0, j = 0;
    for ( i = 0; i <  strlen ( pt -> nomes ); i++ ) {
        if ( pt -> nomes [ i ] == ' ' )
            t++;
    }
    j = strlen ( pt -> nomes ) - t;
    Canvas -> Font -> Color = clBlue;
    Canvas -> TextOut ( 120, 175, "Total de caracteres de nomes" );
    Canvas -> Font -> Color = clRed;
    Canvas -> TextOut ( 450, 175, AnsiString ( j ) );
    if ( x == true ) {
     exit ( 1 );
    free ( pt );
    free ( pt -> name );
    }
}
void __fastcall TForm1::FormCreate ( TObject *Sender ) {
    Canvas -> Pen -> Width = 10;
    Canvas -> Pen -> Color = clYellow;
    Canvas -> Rectangle ( 05, 05, 595, 295 );
    Canvas -> Font -> Size = 13;
    Canvas -> Font -> Name = "arial";
   Canvas -> Font -> Style = TFontStyles() << fsBold << fsUnderline
                       << fsItalic;
    Canvas -> Font -> Color = clRed;
    Canvas -> TextOut ( 140, 15, "OPERADOR SIZEOF  E FUNÇÃO STRLEN" );
   Inf_tam ( Sender );
   Informe ( Sender );
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click ( TObject *Sender ) {
Beep ( 1000, 500 );
x = true;
}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:    // IDE-managed Components
    TButton *Button1;
    void __fastcall Informe ( TObject *Sender );
    void __fastcall Inf_tam ( TObject *Sender );
    void __fastcall FormCreate(TObject *Sender);
    void __fastcall Button1Click(TObject *Sender);
private:    // User declarations
public:     // User declarations
    __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

object Form1: TForm1
  Left = 413
  Top = 118
  Caption = 'OPERADOR SIZEOF  E FUN'#199#195'O STRLEN'
  ClientHeight = 300
  ClientWidth = 600
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnPaint = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 32
    Top = 259
    Width = 49
    Height = 25
    Caption = 'Sair'
    TabOrder = 0
    OnClick = Button1Click
  end
en