Rahul R
Rahul R

Reputation: 207

Anyone know whats the error in following C code

#include <stdio.h>
#include <stdlib.h>
main()
{
    typedef struct
    {
        int info;
        struct strc* next_ptr;
    }strc;
    strc* strcVar[5];
    strcVar = malloc(sizeof(strc) * 5);
    strcVar[0]->info = 1;
    printf(" All is well ");
}

Upvotes: 0

Views: 114

Answers (6)

Kranthi Kumar
Kranthi Kumar

Reputation: 1264

In any array the base address is a const pointer. You cannot change it.

Suppose if you have int a[5];

Here a is the base pointer to the whole array and you are not allowed to change it.

This applies to all the arrays.

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 59987

Change

 strc* strcVar[5];

to

 strc* strcVar;
 strcVar = malloc(sizeof(strc) * 5);
 strcVar[0].info = 1;

OR

Change

strc* strcVar[5];
strcVar = malloc(sizeof(strc) * 5);
strcVar[0]->info = 1;

to

strc strcVar[5];
strcVar[0].info = 1;

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You cannot assign an array from malloc - it's one or the other. If you declared an array of five pointers, the memory for them is allocated already. If you must use malloc, use a pointer to pointer instead of an array. Otherwise, allocate the individual items with malloc, not the array:

strc* strcVar[5];
strcVar[0] = malloc(sizeof(strc));

Upvotes: 2

One Man Crew
One Man Crew

Reputation: 9578

fix code:

#include<stdio.h>
#include<stdlib.h>
void main()
{
    typedef struct
    {
        int info;
        struct strc* next_ptr;
    }strc;
    strc* strcVar;
    strcVar = malloc(sizeof(strc) * 5);
    strcVar[0].info = 1;
    printf(" All is well ");
}

Upvotes: 1

Vaughn Cato
Vaughn Cato

Reputation: 64298

This line is wrong and unnecessary:

strcVar = malloc(sizeof(strc) * 5);

instead you might use:

{
  int i=0;
  for (;i!=5; ++i) {
    strcVar[i] = malloc(sizeof(strc));
  }
}

Upvotes: 2

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

strcVar is a (local) array name, you can't assign a pointer to it. You probably wanted:

 strc* strcVar;
 ... /* and  later */
 strcVar[0].info = 1;

Maybe you wanted an array of pointers to struct strc, then the answer by Vaughn Cato will help.

Upvotes: 2

Related Questions