0

I have already tried using sizeof(a)/sizeof(a[0]) this returns value 0.

I have also tried sizeof(a)/sizeof(Employee) this also have same issue

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

typedef struct Employee_Details
{
    long int Emp_id;
    char Emp_name[200];
    char Emp_city[200];
} Employee;

int main()
{
    Employee *a = (Employee *) malloc(10 * sizeof(Employee));
    int n = sizeof(a);// this should return size of array a =10
                      // but it returns 4
    printf("%d", n);
    free(a);
    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    `a` is a pointer, not array. There's no way to find the number of elements, you have to store it separately. – HolyBlackCat Jul 03 '22 at 06:24
  • The `sizeof` operator (it isn't a function) would report the number of bytes in the object. Even if `a` was an array of 10 `Employee` structures, the size reported would probably 4040 or 4080 bytes — it would categorically not be `10`. – Jonathan Leffler Jul 03 '22 at 06:28
  • @JonathanLeffler Sir, but when I try to use sizeof operator on a to get the number of bytes it gives 4 instead of 4040. – Sahilpervez Alam Jul 03 '22 at 06:44
  • Yes, it would. That is, on a 32-bit machine, `sizeof(a)` is bound to return `4` because `a` is a pointer. Note that I said "_IF_ `a` was an array of 10 `Employee` structures", but it isn't. It's a pointer, and on your 32-bit machine, a pointer is 4 bytes long. So the size of `a` will be 4 (on a 332-bit machine; 8 on a 64-bit machine). C does not record the sizes of allocations made by `malloc()` where you can access it; you must track the size allocated yourself. And, as I said (or at least intimated), `sizeof` returns a byte count — not the number of elements (except for 'byte' types). – Jonathan Leffler Jul 03 '22 at 07:04

0 Answers0