Thread: inputting elements inside a 2 dimensional dynamically allocated array

  1. #1
    Registered User
    Join Date
    May 2020
    Posts
    3

    inputting elements inside a 2 dimensional dynamically allocated array

    i want to input elements inside a 2 dimensional dynamically allocated array but unfortunatley it inputs only half of the elements of the declared size here is the code
    Code:
    #include<stdio.h>
    #include<stdlb.h>
    int main(){
        int i,r,c;     // no of rows and columns
        scanf("%d",&r);
        scanf("%d",&c);
        int n=r*c;   // n is the total no of elements
        char**arr=malloc(r*c*sizeof(char*));
        for(i=0;i<n;++i)
        {
            scanf("%c",&arr[i]);
        }
         free(arr);
         return 0;
    }

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,629
    Note that scanf("%c", &a[i]); will read the very next character, even if it's a space, tab, or newline. If you want to skip whitespace, put a space before the %c:
    Code:
    scanf(" %c", &a[i]);
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > char**arr=malloc(r*c*sizeof(char*));
    This should be
    char *arr = malloc(r*c*sizeof(char*));
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 01-15-2011, 01:47 PM
  2. Two dimensional dynamically allocated array problem
    By binaryboy in forum C++ Programming
    Replies: 5
    Last Post: 08-19-2009, 11:35 AM
  3. Dynamically allocated array
    By dre in forum C Programming
    Replies: 17
    Last Post: 08-13-2009, 06:57 PM
  4. Replies: 2
    Last Post: 11-28-2008, 05:15 PM
  5. Dynamically Allocated Array
    By vb.bajpai in forum C Programming
    Replies: 3
    Last Post: 06-17-2007, 08:40 AM

Tags for this Thread