C言語でのReallocとは何ですか?
Cライブラリのメモリ割り当て関数void*realloc(void * ptr、size_t size)は、mallocまたはcallocの呼び出しで以前に割り当てられたptrが指すメモリブロックのサイズを変更しようとします。
メモリ割り当て関数
以下に説明するように、メモリは2つの方法で割り当てることができます-
コンパイル時にメモリが割り当てられると、実行中にメモリを変更することはできません。不十分であるか、そうでなければメモリの浪費の問題があります。
解決策は、動的に、つまりプログラムの実行中のユーザーの要件に従ってメモリを作成することです。
動的メモリ管理に使用される標準ライブラリ関数は次のとおりです-
- malloc()
- calloc()
- realloc()
- 無料()
realloc()関数
-
すでに割り当てられているメモリを再割り当てするために使用されます。
-
割り当てられたメモリを増減できます。
-
再割り当てされたメモリのベースアドレスを指すvoidポインタを返します。
realloc()関数の構文は次のとおりです-
Free void *realloc (pointer, newsize);
例
次の例は、realloc()関数の使用法を示しています。
int *ptr; ptr = (int * ) malloc (1000);// we can use calloc also - - - - - - - - - ptr = (int * ) realloc (ptr, 500); - - - - - - ptr = (int * ) realloc (ptr, 1500);
例
以下に、realloc()関数を使用するCプログラムを示します-
#include<stdio.h> #include<stdlib.h> int main(){ int *ptr, i, num; printf("array size is 5\n"); ptr = (int*)calloc(5, sizeof(int)); if(ptr==NULL){ printf("Memory allocation failed"); exit(1); // exit the program } for(i = 0; i < 5; i++){ printf("enter number at %d: ", i); scanf("%d", ptr+i); } printf("\nLet's increase the array size to 7\n "); ptr = (int*)realloc(ptr, 7 * sizeof(int)); if(ptr==NULL){ printf("Memory allocation failed"); exit(1); // exit the program } printf("\n enter 2 more integers\n\n"); for(i = 5; i < 7; i++){ printf("Enter element number at %d: ", i); scanf("%d", ptr+i); } printf("\n result array is: \n\n"); for(i = 0; i < 7; i++){ printf("%d ", *(ptr+i) ); } return 0; }
出力
上記のプログラムを実行すると、次の結果が得られます-
array size is 5 enter number at 0: 23 enter number at 1: 12 enter number at 2: 45 enter number at 3: 67 enter number at 4: 20 Let's increase the array size to 7 enter 2 more integers Enter element number at 5: 90 Enter element number at 6: 60 result array is: 23 12 45 67 20 90 60
-
C言語のstrcmp()関数とは何ですか?
Cライブラリ関数intstrcmp(const char * str1、const char * str2) str1が指す文字列を比較します str2が指す文字列へ 。 文字の配列は文字列と呼ばれます。 宣言 以下は配列の宣言です- char stringname [size]; 例-charstring[50];長さ50文字の文字列 初期化 単一文字定数の使用- char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,&ls
-
C#プログラミングとは何ですか?
C#は、Microsoftによって開発された最新の汎用オブジェクト指向プログラミング言語です。 C#は、共通言語インフラストラクチャ(CLI)用に設計されています。これは、実行可能コードとランタイム環境で構成されており、さまざまなコンピュータープラットフォームやアーキテクチャでさまざまな高級言語を使用できます。 C#の機能は次のとおりです- ブール条件 自動ガベージコレクション 標準ライブラリ アセンブリのバージョン管理 プロパティとイベント デリゲートとイベント管理 使いやすいジェネリック インデクサー 条件付きコンパイル シンプルなマルチスレッド LINQおよびLambda式 Win