C - Declare and Print Dynamic Array using C Pointer.


IncludeHelp 03 August 2016

In this code snippet, we will learn how to declare dynamic memory for one dimensional integer array. In this example, we will declare dynamic array for 5 integer elements, assigning values to them and print values of all elements.

C Code Snippet - Declare and Print Dynamic Array using C Pointer

//C - Declare and Print Dynamic Array using C Pointer.

#include <stdio.h>
#include <stdlib.h>

int main(){
	int *ptr,i;
	
	ptr=(int*)malloc(5*sizeof(int));
	if(ptr==NULL){
		printf("Error in allocating memory!!!");
		return -1;
	}
	*(ptr+0)=10; *(ptr+1)=20; *(ptr+2)=30; *(ptr+3)=40;
	*(ptr+4)=50;
	
	printf("Array elements are:\n");
	
	for(i=0;i<5;i++){
		printf("%d ",*(ptr+i));
	}
	
    return 0;	
}

    Array elements are:
    10 20 30 40 50



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.