C言語での動的メモリ割り当て機能のサンプルプログラム
問題
C言語の動的メモリ割り当て関数を使用してn個の数値の合計を表示および計算するにはどうすればよいですか?
解決策
以下は、動的メモリ割り当て関数を使用して、要素を表示し、ユーザーがn個の数値の合計を計算するCプログラムです。ここでは、メモリの浪費を減らすことも試みています。
例
#include<stdio.h>
#include<stdlib.h>
void main(){
//Declaring variables and pointers,sum//
int numofe,i,sum=0;
int *p;
//Reading number of elements from user//
printf("Enter the number of elements : ");
scanf("%d",&numofe);
//Calling malloc() function//
p=(int *)malloc(numofe*sizeof(int));
/*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/
if (p==NULL){
printf("Memory not available");
exit(0);
}
//Printing elements//
printf("Enter the elements : \n");
for(i=0;i<numofe;i++){
scanf("%d",p+i);
sum=sum+*(p+i);
}
printf("\nThe sum of elements is %d",sum);
free(p);//Erase first 2 memory locations//
printf("\nDisplaying the cleared out memory location : \n");
for(i=0;i<numofe;i++){
printf("%d\n",p[i]);//Garbage values will be displayed//
}
} 出力
上記のプログラムを実行すると、次の結果が得られます-
Enter the number of elements: 4 Enter the elements: 23 45 67 89 The sum of elements is 224 Displaying the cleared out memory location: 7410816 0 7405904 0
-
C言語のisupper()関数
関数isupper()は、文字が大文字であるかどうかを確認するために使用されます。それ以外の場合は成功した場合はゼロ以外の値を返し、それ以外の場合はゼロを返します。 「ctype.h」ヘッダーファイルで宣言されています。 これがC言語でのisupper()の構文です int isupper(int character); ここで キャラクター −チェックする文字。 これがC言語のisupper()の例です 例 #include<stdio.h> #include<ctype.h> int main() { char val1 =
-
C言語のisalnum()関数
関数isalnum()は、文字が英数字であるかどうかを確認するために使用されます。文字が英数字の場合は文字または数字を意味し、それ以外の場合はゼロを返します。 「ctype.h」ヘッダーファイルで宣言されています。 これがC言語のisalnum()の構文です int isalnum(int character); ここで キャラクター −チェックする文字。 これがC言語のisalnum()の例です 例 #include<stdio.h> #include<ctype.h> int main() { char val1 = 's&