logo

Typy danych w C

Typ danych określa typ danych, które zmienna może przechowywać, np. liczba całkowita, liczba zmiennoprzecinkowa, znak itp.

Typy danych C

W języku C istnieją następujące typy danych.

TypyTypy danych
Podstawowy typ danychint, char, float, double
Pochodny typ danychtablica, wskaźnik, struktura, unia
Typ danych wyliczeniowychwyliczenie
Unieważniony typ danychpróżnia

Podstawowe typy danych

Podstawowe typy danych to liczby całkowite i zmiennoprzecinkowe. Język C obsługuje zarówno literały ze znakiem, jak i bez znaku.

Rozmiar pamięci podstawowych typów danych może się zmieniać w zależności od 32- lub 64-bitowego systemu operacyjnego.

znak tostring Java

Zobaczmy podstawowe typy danych. Podany jest jego rozmiar zgodnie z architekturą 32-bitową .

Typy danychRozmiar pamięciZakres
zwęglać 1 bajt-128 do 127
podpisany znak1 bajt-128 do 127
znak bez znaku1 bajt0 do 255
krótki 2 bajty-32 768 do 32 767
podpisany krótko2 bajty-32 768 do 32 767
krótki bez znaku2 bajty0 do 65 535
wew 2 bajty-32 768 do 32 767
podpisał się m.in2 bajty-32 768 do 32 767
bez znaku int2 bajty0 do 65 535
krótki wew 2 bajty-32 768 do 32 767
podpisał krótki in2 bajty-32 768 do 32 767
krótki int bez znaku2 bajty0 do 65 535
długi wew 4 bajty-2 147 483 648 do 2 147 483 647
podpisany długo wew4 bajty-2 147 483 648 do 2 147 483 647
długi int bez znaku4 bajty0 do 4 294 967 295
platforma 4 bajty
podwójnie 8 bajtów
długi podwójny 10 bajtów

Wewnętrzne:

Liczby całkowite są liczbami całkowitymi bez części ułamkowych i dziesiętnych, oraz int typ danych służy do ich reprezentowania.

Jest często stosowany do zmiennych, które obejmują wartości , Jak na przykład liczy, indeksy lub inne liczby liczbowe. The int typ danych może reprezentować oba pozytywny I liczby ujemne ponieważ jest domyślnie podpisany.

Jakiś wew zajmuje 4 bajty pamięci w większości urządzeń, co pozwala na przechowywanie wartości od około -2 miliardów do +2 miliardów.

Zwęglać:

Poszczególne znaki są reprezentowane przez typ danych char . Zwykle używany do trzymania ASCII Lub Znaki schematu kodowania UTF-8 , Jak na przykład litery, cyfry, symbole , Lub przecinki . Tam są 256 znaków który może być reprezentowany przez pojedynczy znak, który zajmuje jeden bajt pamięci. Postacie takie jak „A”, „b”, „5”, Lub „$” są ujęte w pojedyncze cudzysłowy.

Platforma:

Aby reprezentować liczby całkowite, użyj zmienny typ danych . Liczb zmiennoprzecinkowych można używać do reprezentowania jednostek ułamkowych lub liczb z miejscami dziesiętnymi.

The typ pływający jest zwykle używany do zmiennych, które wymagają bardzo dużej precyzji, ale mogą nie być bardzo dokładne. Może przechowywać wartości z dokładnością do ok 6 miejsc po przecinku i zakres ok 3,4x1038 W 4 bajty pamięciowy.

parseint Java

Podwójnie:

Użyj dwóch typów danych do reprezentacji dwie zmienne liczby całkowite . Gdy wymagana jest dodatkowa precyzja, na przykład w obliczeniach naukowych lub zastosowaniach finansowych, zapewnia większą dokładność w porównaniu do pływaka.

Typ podwójny , który korzysta 8 bajtów pamięci i ma dokładność ok 15 miejsc po przecinku, daje większe wartości . C domyślnie traktuje liczby zmiennoprzecinkowe jako liczby podwójne, jeśli nie podano jawnego typu.

 int age = 25; char grade = 'A'; float temperature = 98.6; double pi = 3.14159265359; 

W powyższym przykładzie deklarujemy cztery zmienne: an zmienna int dla wieku danej osoby, a zmienna char za ocenę ucznia, a zmienna pływająca do odczytu temperatury i dwie zmienne do liczba pi.

Pochodny typ danych

Oprócz podstawowych typów danych, C obsługuje również pochodne typy danych, w tym tablice, wskaźniki, struktury, I związki . Te typy danych dają programistom możliwość obsługi heterogenicznych danych, bezpośredniego modyfikowania pamięci i tworzenia skomplikowanych struktur danych.

Szyk:

Jakiś array, pochodny typ danych , pozwala przechowywać sekwencję elementy o stałym rozmiarze tego samego typu. Zapewnia mechanizm łączenia wielu celów tych samych danych pod tą samą nazwą.

Indeks służy do uzyskiwania dostępu do elementów tablicy za pomocą a 0 indeks dla pierwszego wpisu. Rozmiar tablicy jest stały w momencie deklaracji i nie można go zmienić podczas wykonywania programu. Składniki tablicy są umieszczane w sąsiednich obszarach pamięci.

Oto przykład zadeklarowania i wykorzystania tablicy:

 #include int main() { int numbers[5]; // Declares an integer array with a size of 5 elements // Assign values to the array elements numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; // Display the values stored in the array printf(&apos;Values in the array: &apos;); for (int i = 0; i <5; i++) { printf('%d ', numbers[i]); } printf('
'); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> Values in the array: 10 20 30 40 50 </pre> <h3>Pointer:</h3> <p>A <strong> <em>pointer</em> </strong> is a derived data type that keeps track of another data type&apos;s memory address. When a <strong> <em>pointer</em> </strong> is declared, the <strong> <em>data type</em> </strong> it refers to is <strong> <em>stated first</em> </strong> , and then the <strong> <em>variable name</em> </strong> is preceded by <strong> <em>an asterisk (*)</em> </strong> .</p> <p>You can have incorrect access and change the value of variable using pointers by specifying the memory address of the variable. <strong> <em>Pointers</em> </strong> are commonly used in <strong> <em>tasks</em> </strong> such as <strong> <em>function pointers, data structures</em> </strong> , and <strong> <em>dynamic memory allocation</em> </strong> .</p> <p>Here is an example of declaring and employing a pointer:</p> <pre> #include int main() { int num = 42; // An integer variable int *ptr; // Declares a pointer to an integer ptr = # // Assigns the address of &apos;num&apos; to the pointer // Accessing the value of &apos;num&apos; using the pointer printf(&apos;Value of num: %d
&apos;, *ptr); return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> Value of num: 42 </pre> <h3>Structure:</h3> <p>A structure is a derived data type that enables the creation of composite data types by allowing the grouping of many data types under a single name. It gives you the ability to create your own unique data structures by fusing together variables of various sorts.</p> <ol class="points"> <li>A structure&apos;s members or fields are used to refer to each variable within it.</li> <li>Any data type, including different structures, can be a member of a structure.</li> <li>A structure&apos;s members can be accessed by using the dot (.) operator.</li> </ol> <p>A declaration and use of a structure is demonstrated here:</p> <pre> #include #include // Define a structure representing a person struct Person { char name[50]; int age; float height; }; int main() { // Declare a variable of type struct Person struct Person person1; // Assign values to the structure members strcpy(person1.name, &apos;John Doe&apos;); person1.age = 30; person1.height = 1.8; // Accessing the structure members printf(&apos;Name: %s
&apos;, person1.name); printf(&apos;Age: %d
&apos;, person1.age); printf(&apos;Height: %.2f
&apos;, person1.height); return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> Name: John Doe Age: 30 Height: 1.80 </pre> <h3>Union:</h3> <p>A derived data type called a <strong> <em>union</em> </strong> enables you to store various data types in the same memory address. In contrast to structures, where each member has a separate memory space, members of a union all share a single memory space. A value can only be held by one member of a union at any given moment. When you need to represent many data types interchangeably, unions come in handy. Like structures, you can access the members of a union by using the <strong> <em>dot (.)</em> </strong> operator.</p> <p>Here is an example of a union being declared and used:</p> <pre> #include // Define a union representing a numeric value union NumericValue { int intValue; float floatValue; char stringValue[20]; }; int main() { // Declare a variable of type union NumericValue union NumericValue value; // Assign a value to the union value.intValue = 42; // Accessing the union members printf(&apos;Integer Value: %d
&apos;, value.intValue); // Assigning a different value to the union value.floatValue = 3.14; // Accessing the union members printf(&apos;Float Value: %.2f
&apos;, value.floatValue); return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> Integer Value: 42 Float Value: 3.14 </pre> <h2>Enumeration Data Type</h2> <p>A set of named constants or <strong> <em>enumerators</em> </strong> that represent a collection of connected values can be defined in C using the <strong> <em>enumeration data type (enum). Enumerations</em> </strong> give you the means to give names that make sense to a group of integral values, which makes your code easier to read and maintain. </p> <p>Here is an example of how to define and use an enumeration in C:</p> <pre> #include // Define an enumeration for days of the week enum DaysOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; int main() { // Declare a variable of type enum DaysOfWeek enum DaysOfWeek today; // Assign a value from the enumeration today = Wednesday; // Accessing the enumeration value printf(&apos;Today is %d
&apos;, today); return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> Today is 2 </pre> <h2>Void Data Type</h2> <p>The <strong> <em>void data type</em> </strong> in the C language is used to denote the lack of a particular type. <strong> <em>Function return types, function parameters</em> </strong> , and <strong> <em>pointers</em> </strong> are three situations where it is frequently utilized.</p> <h3>Function Return Type:</h3> <p>A <strong> <em>void return type</em> </strong> function does not produce a value. A <strong> <em>void function</em> </strong> executes a task or action and ends rather than returning a value.</p> <p> <strong>Example:</strong> </p> <pre> void printHello() { printf(&apos;Hello, world!
&apos;); } </pre> <h3>Function Parameters: </h3> <p>The <strong> <em>parameter void</em> </strong> can be used to indicate that a function accepts no arguments.</p> <p> <strong>Example:</strong> </p> <pre> void processInput(void) { /* Function logic */ } </pre> <h3>Pointers:</h3> <p>Any address can be stored in a pointer of type <strong> <em>void*</em> </strong> , making it a universal pointer. It offers a method for working with pointers to ambiguous or atypical types.</p> <p> <strong>Example:</strong> </p> <pre> void* dataPtr; </pre> <p>The <strong> <em>void data type</em> </strong> is helpful for defining functions that don&apos;t accept any arguments when working with generic pointers or when you wish to signal that a function doesn&apos;t return a value. It is significant to note that while <strong> <em>void*</em> </strong> can be used to build generic pointers, void itself cannot be declared as a variable type.</p> <p>Here is a sample of code that shows how to utilize void in various situations:</p> <pre> #include // Function with void return type void printHello() { printf(&apos;Hello, world!
&apos;); } // Function with void parameter void processInput(void) { printf(&apos;Processing input...
&apos;); } int main() { // Calling a void function printHello(); // Calling a function with void parameter processInput(); // Using a void pointer int number = 10; void* dataPtr = &amp;number; printf(&apos;Value of number: %d
&apos;, *(int*)dataPtr); return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> Hello, world! Processing input... Value of number: 10 </pre> <h2>Conclusion:</h2> <p>As a result, <strong> <em>data types</em> </strong> are essential in the C programming language because they define the kinds of information that variables can hold. They provide the data&apos;s size and format, enabling the compiler to allot memory and carry out the necessary actions. Data types supported by C include <strong> <em>void, enumeration, derived</em> </strong> , and <strong> <em>basic types</em> </strong> . In addition to floating-point types like <strong> <em>float</em> </strong> and <strong> <em>double</em> </strong> , basic data types in C also include integer-based kinds like <strong> <em>int, char</em> </strong> , and <strong> <em>short</em> </strong> . These forms can be <strong> <em>signed</em> </strong> or <strong> <em>unsigned</em> </strong> , and they fluctuate in size and range. To create dependable and efficient code, it is crucial to comprehend the memory size and scope of these types.</p> <p>A few examples of <strong> <em>derived data types</em> </strong> are <strong> <em>unions, pointers, structures</em> </strong> , and <strong> <em>arrays</em> </strong> . Multiple elements of the same kind can be stored together in contiguous memory due to arrays. <strong> <em>Pointers</em> </strong> keep track of memory addresses, allowing for fast data structure operations and dynamic memory allocation. While <strong> <em>unions</em> </strong> allow numerous variables to share the same memory space, structures group relevant variables together.</p> <p> <strong> <em>Code</em> </strong> becomes more legible and maintainable when named constants are defined using enumeration data types. <strong> <em>Enumerations</em> </strong> give named constants integer values to enable the meaningful representation of related data. The void data type indicates the lack of a particular type. It is used as a return type for both <strong> <em>functions</em> </strong> and <strong> <em>function parameters</em> </strong> that don&apos;t take any arguments and don&apos;t return a value. The <strong> <em>void* pointer</em> </strong> also functions as a general pointer that can <strong> <em>store addresses</em> </strong> of various types.</p> <p>C programming requires a solid understanding of <strong> <em>data types</em> </strong> . Programmers can ensure adequate memory allocation, avoid <strong> <em>data overflow</em> </strong> or <strong> <em>truncation</em> </strong> , and enhance the readability and maintainability of their code by selecting the right <strong> <em>data type</em> </strong> . C programmers may create <strong> <em>effective, dependable</em> </strong> , and well-structured code that satisfies the requirements of their applications by having a firm understanding of data types.</p> <hr></5;>

Wskaźnik:

A wskaźnik to pochodny typ danych, który śledzi adres pamięci innego typu danych. Kiedy wskaźnik ogłasza się, typ danych odnosi się do jest stwierdził jako pierwszy , a następnie nazwa zmiennej jest poprzedzone gwiazdka (*) .

Można mieć nieprawidłowy dostęp i zmieniać wartość zmiennej za pomocą wskaźników, podając adres pamięci zmiennej. Wskaźniki są powszechnie stosowane w zadania Jak na przykład wskaźniki funkcji, struktury danych , I dynamiczna alokacja pamięci .

Oto przykład deklaracji i użycia wskaźnika:

 #include int main() { int num = 42; // An integer variable int *ptr; // Declares a pointer to an integer ptr = # // Assigns the address of &apos;num&apos; to the pointer // Accessing the value of &apos;num&apos; using the pointer printf(&apos;Value of num: %d
&apos;, *ptr); return 0; } 

Wyjście:

 Value of num: 42 

Struktura:

Struktura to pochodny typ danych, który umożliwia tworzenie złożonych typów danych, umożliwiając grupowanie wielu typów danych pod jedną nazwą. Daje możliwość tworzenia własnych, unikalnych struktur danych poprzez łączenie ze sobą różnego rodzaju zmiennych.

połącz bazę danych Java
  1. Elementy lub pola struktury służą do odwoływania się do każdej zmiennej w niej zawartej.
  2. Dowolny typ danych, w tym różne struktury, może być członkiem struktury.
  3. Dostęp do elementów struktury można uzyskać za pomocą operatora kropki (.).

Deklarację i użycie struktury pokazano tutaj:

 #include #include // Define a structure representing a person struct Person { char name[50]; int age; float height; }; int main() { // Declare a variable of type struct Person struct Person person1; // Assign values to the structure members strcpy(person1.name, &apos;John Doe&apos;); person1.age = 30; person1.height = 1.8; // Accessing the structure members printf(&apos;Name: %s
&apos;, person1.name); printf(&apos;Age: %d
&apos;, person1.age); printf(&apos;Height: %.2f
&apos;, person1.height); return 0; } 

Wyjście:

 Name: John Doe Age: 30 Height: 1.80 

Unia:

Pochodny typ danych zwany a unia umożliwia przechowywanie różnych typów danych pod tym samym adresem pamięci. W przeciwieństwie do struktur, w których każdy członek ma oddzielną przestrzeń pamięci, wszyscy członkowie związku współdzielą jedną przestrzeń pamięci. Wartość może być wyznaczona w danym momencie tylko przez jednego członka związku. Gdy trzeba reprezentować wiele typów danych zamiennie, przydatne są unie. Podobnie jak w przypadku struktur, dostęp do członków związku można uzyskać za pomocą opcji kropka (.) operator.

Oto przykład deklaracji i użycia unii:

 #include // Define a union representing a numeric value union NumericValue { int intValue; float floatValue; char stringValue[20]; }; int main() { // Declare a variable of type union NumericValue union NumericValue value; // Assign a value to the union value.intValue = 42; // Accessing the union members printf(&apos;Integer Value: %d
&apos;, value.intValue); // Assigning a different value to the union value.floatValue = 3.14; // Accessing the union members printf(&apos;Float Value: %.2f
&apos;, value.floatValue); return 0; } 

Wyjście:

 Integer Value: 42 Float Value: 3.14 

Typ danych wyliczeniowych

Zestaw nazwanych stałych lub rachmistrzowie które reprezentują zbiór połączonych wartości, można zdefiniować w C za pomocą typ danych wyliczeniowych (enum). Wyliczenia daje możliwość nadawania nazw, które mają sens grupie wartości całkowitych, co sprawia, że ​​kod jest łatwiejszy do odczytania i utrzymania.

Oto przykład definiowania i używania wyliczenia w C:

liczba całkowita Java
 #include // Define an enumeration for days of the week enum DaysOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; int main() { // Declare a variable of type enum DaysOfWeek enum DaysOfWeek today; // Assign a value from the enumeration today = Wednesday; // Accessing the enumeration value printf(&apos;Today is %d
&apos;, today); return 0; } 

Wyjście:

 Today is 2 

Unieważniony typ danych

The pusty typ danych w języku C służy do oznaczenia braku określonego typu. Typy zwracanych funkcji, parametry funkcji , I wskazówki to trzy sytuacje, w których jest on często używany.

Typ powrotu funkcji:

A pusty typ zwrotu funkcja nie generuje wartości. A funkcja pusta wykonuje zadanie lub akcję i kończy się, zamiast zwracać wartość.

Przykład:

 void printHello() { printf(&apos;Hello, world!
&apos;); } 

Parametry funkcji:

The parametr nieważny może służyć do wskazania, że ​​funkcja nie przyjmuje żadnych argumentów.

Przykład:

 void processInput(void) { /* Function logic */ } 

Wskazówki:

Dowolny adres można zapisać we wskaźniku typu próżnia* , co czyni go uniwersalnym wskaźnikiem. Oferuje metodę pracy ze wskaźnikami do typów niejednoznacznych lub nietypowych.

Przykład:

 void* dataPtr; 

The pusty typ danych jest pomocny przy definiowaniu funkcji, które nie akceptują żadnych argumentów podczas pracy ze wskaźnikami ogólnymi lub gdy chcesz zasygnalizować, że funkcja nie zwraca wartości. Warto zauważyć, że podczas próżnia* można używać do budowania ogólnych wskaźników, samej wartości void nie można zadeklarować jako typu zmiennej.

Oto przykładowy kod pokazujący, jak wykorzystać void w różnych sytuacjach:

 #include // Function with void return type void printHello() { printf(&apos;Hello, world!
&apos;); } // Function with void parameter void processInput(void) { printf(&apos;Processing input...
&apos;); } int main() { // Calling a void function printHello(); // Calling a function with void parameter processInput(); // Using a void pointer int number = 10; void* dataPtr = &amp;number; printf(&apos;Value of number: %d
&apos;, *(int*)dataPtr); return 0; } 

Wyjście:

 Hello, world! Processing input... Value of number: 10 

Wniosek:

W rezultacie, typy danych są niezbędne w języku programowania C, ponieważ definiują rodzaje informacji, które mogą przechowywać zmienne. Podają rozmiar i format danych, umożliwiając kompilatorowi przydzielenie pamięci i wykonanie niezbędnych działań. Typy danych obsługiwane przez C obejmują nieważne, wyliczenie, pochodne , I podstawowe typy . Oprócz typów zmiennoprzecinkowych, takich jak platforma I podwójnie , podstawowe typy danych w C obejmują również typy oparte na liczbach całkowitych, takie jak int, znak , I krótki . Formy te mogą być podpisany Lub niepodpisany i zmieniają się pod względem wielkości i zasięgu. Aby stworzyć niezawodny i wydajny kod, ważne jest zrozumienie rozmiaru pamięci i zakresu tego typu.

testy regresyjne w testowaniu oprogramowania

Kilka przykładów pochodne typy danych Czy unie, wskaźniki, struktury , I tablice . Wiele elementów tego samego rodzaju można przechowywać razem w ciągłej pamięci dzięki tablicom. Wskaźniki śledzić adresy pamięci, co pozwala na szybkie operacje na strukturze danych i dynamiczną alokację pamięci. Chwila związki pozwalają wielu zmiennym dzielić tę samą przestrzeń pamięci, struktury grupują razem odpowiednie zmienne.

Kod staje się bardziej czytelny i łatwiejszy w utrzymaniu, gdy nazwane stałe są zdefiniowane przy użyciu wyliczeniowych typów danych. Wyliczenia nadaj nazwanym stałym wartości całkowite, aby umożliwić znaczącą reprezentację powiązanych danych. Typ danych void wskazuje na brak określonego typu. Jest używany jako typ zwracany dla obu Funkcje I parametry funkcji które nie przyjmują żadnych argumentów i nie zwracają wartości. The pusty* wskaźnik działa również jako ogólny wskaźnik, który może adresy sklepów różnych typów.

Programowanie w C wymaga solidnego zrozumienia typy danych . Programiści mogą zapewnić odpowiednią alokację pamięci, unikając przepełnienie danych Lub obcięcie i zwiększ czytelność i łatwość konserwacji swojego kodu, wybierając odpowiednią opcję typ danych . Programiści C mogą tworzyć skuteczny, niezawodny oraz dobrze zorganizowany kod, który spełnia wymagania aplikacji dzięki dokładnemu zrozumieniu typów danych.