Skip to main content

Command Palette

Search for a command to run...

struct pointer vs struct variable

Published
2 min readView as Markdown
struct pointer vs struct variable
X

"I am currently a Software Engineering student at ALX. I'm passionate about technology and enjoy conducting research to find answers on my own. I have a natural inclination to ask 'WHY' more often than 'HOW'.

"While working on projects at ALX, I have acquired a wealth of interesting and diverse knowledge about software engineering and computer science in general. Therefore, I needed a place to store and save all this information, allowing me to refer back to it whenever I forget."

If hash_s is a struct

difference between 'hash_s *a' and 'hash_s b':

In C programming, when you declare a pointer variable using the asterisk (*) symbol, such as hash_s *a, you are creating a variable a that can hold a memory address. In this case, hash_s *a is a pointer to a struct of type hash_s. It means that a can store the memory address of a hash_s struct, but it doesn't allocate memory for the struct itself.

On the other hand, when you declare a variable without the asterisk symbol, such as hash_s b, you are creating an actual variable b that will store the struct directly. In this case, memory is allocated for the hash_s struct automatically and the variable b can hold the values of the struct members.

To summarize:

  • hash_s *a is a pointer to a hash_s struct, and it needs to be assigned a valid memory address using dynamic memory allocation (e.g., with malloc) or by pointing it to an existing struct.

  • hash_s b is a variable of type hash_s that directly holds the struct's values. Memory for b is automatically allocated.

Here's an example to illustrate the difference:

#include <stdlib.h>

typedef struct {
    int value;
} hash_s;

int main() {
    hash_s *a;      // Pointer to hash_s struct
    hash_s b;       // hash_s struct variable

    a = (hash_s*)malloc(sizeof(hash_s));  // Allocate memory for a hash_s struct

    a->value = 10;  // Access the value using the pointer and arrow operator
    b.value = 20;   // Access the value directly using the variable

    free(a);        // Free the allocated memory

    return 0;
}

In this example, a is a pointer to a hash_s struct that is dynamically allocated using malloc, while b is a hash_s struct variable that is directly allocated on the stack.

More from this blog

PERSONAL BLOG

110 posts

Use the search button to search for a specific topic or keyword *all posts are updated on the go*