top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to create dynamic array in C?

+2 votes
How to create dynamic array in C?
posted May 5, 2014 by Vishvachi Tiwari

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

Creating 1-D array:---- int type

int n=getSize();
int *arr=( int * ) malloc ( sizeof ( int )  *  n);
//Do Some Stuff :)
//reallocating the same array.... making the size change:-
m=getSize();     //Getting the new size
arr=(int *) realloc(arr,m);   //You can assign it to any pointer to an integer variable

2-D array:-With Number of rows and number of columns unknown

int n= getRows();
int m=getColumns();
int **arr=NULL;
arr=(int **)malloc(sizeof(int *) * n);
for ( int i=0;i<n;i++){
   arr[i]=(int *) malloc(sizeof(int) * m);

2-D With Number of Columns Unknown but number of rows known say 10:
This can give you variable number of columns

int *arr[10];
for(int i=0;i<10;i++){
    arr[i]=(int *)malloc(sizeof(int) * m);

Try for number of rows Unknown urself :) An exercise :) Use pointer to an array.

answer May 5, 2014 by Prakash
Similar Questions
+4 votes
printf ("%s %d %f\n", (*ptr+i).a, (*ptr+i).b, (*ptr+i).c);
[Error] invalid operands to binary + (have 'struct name' and 'int')

where ptr is a pointer to the structure and allocated dynamic memory using malloc. Any suggestion would be helpful.

Thanks in advance.

0 votes

Trivial question, please help.

I need to convert a string literal like "111.25" to floating point number.
atof() fails me as it returns 1111 and discards .25?

+1 vote

How to create a c program to print a alphabet in the form of stars for ex.
A should be printed something like

  * *
*     *

Do we have any standard algo???

+2 votes

Please share a sample program with detail code.

+1 vote

int arr[ ] = { 1, 2 };
p = arr; /* p is pointing to arr */

How pointer p will behave ?

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.