top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

C: How to accessing structure member through pointer using dynamic memory allocation?

+4 votes
320 views
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.

posted Sep 22, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
#include<stdlib.h>

struct name {
   int a;
   float b;
   char c[30];
};

int main() {
   struct name *ptr;
   int i,n;

   printf("Enter n: ");
   scanf("%d",&n);

   ptr=(struct name*)malloc(n*sizeof(struct name));

  /* Above statement allocates the memory for n structures with pointer ptr pointing to base address */
   for(i=0;i<n;++i){
       printf("Enter string, integer and floating number  respectively:\n");
       scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);
   }

   printf("Displaying Information:\n");
   for(i=0;i<n;++i)
       printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);

   return 0;
}
answer Nov 4, 2015 by Shivaranjini
Similar Questions
+1 vote

I have written a simple program and stored it with .c file,
When i compiled it with g++ it is getting compiled and giving the proper output when i run that,
but when i compile the same using gcc then it is throwing error.

Below is the sample .c file
#include<stdio.h>
struct A{
        private:
        int a;
        public:
        int sum(){
        a=10;
        }
        void print()
        {
        printf("%d\n",a);
        }
        A()
        {
                printf("Constructor\n");
        }
        A(int b)
        {
                printf("Copy Constructor\n");
        }
        ~A()
        {
                printf("Destructor\n");
        }
};
main()
{
        struct A a(10);
        a.sum();
        a.print();
}
+3 votes
main {
 int a;
 a = 10;
}

Here, when the memory will be allocated.
Compile/Run time? why ?

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...