Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9268657
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T14:54:46+00:00 2026-06-18T14:54:46+00:00

Suppose I want to define a structure representing length of the vector and its

  • 0

Suppose I want to define a structure representing length of the vector and its values as:

struct Vector{
    double* x;
    int n;
};

Now, suppose I want to define a vector y and allocate memory for it.

struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector));

My search over the internet show that I should allocate the memory for x separately.

y->x = (double*)malloc(10*sizeof(double));

But, it seems that I am allocating the memory for y->x twice, one while allocating memory for y and the other while allocating memory for y->x, and it seems a waste of memory.
It is very much appreciated if let me know what compiler really do and what would be the right way to
initialize both y, and y->x.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T14:54:48+00:00Added an answer on June 18, 2026 at 2:54 pm

    No, you’re not allocating memory for y->x twice.

    Instead, you’re allocating memory for the structure (which includes a pointer) plus something for that pointer to point to.

    Think of it this way:

             1          2
            +-----+    +------+
    y------>|  x------>|  *x  |
            |  n  |    +------+
            +-----+
    

    You actually need the two allocations (1 and 2) to store everything you need.

    Additionally, your type should be struct Vector *y since it’s a pointer, and you should never cast the return value from malloc in C.

    It can hide certain problems you don’t want hidden, and C is perfectly capable of implicitly converting the void* return value to any other pointer.

    And, of course, you probably want to encapsulate the creation of these vectors to make management of them easier, such as with having the following in a header file vector.h:

    struct Vector {
        double *data;    // Use readable names rather than x/n.
        size_t size;
    };
    
    struct Vector *newVector(size_t sz);
    void delVector(struct Vector *vector);
    //void setVectorItem(struct Vector *vector, size_t idx, double val);
    //double getVectorItem(struct Vector *vector, size_t idx);
    

    Then, in vector.c, you have the actual functions for managing the vectors:

    #include "vector.h"
    
    // Atomically allocate a two-layer object. Either both layers
    // are allocated or neither is, simplifying memory checking.
    
    struct Vector *newVector(size_t sz) {
        // First, the vector layer.
    
        struct Vector *vector = malloc(sizeof (struct Vector));
        if (vector == NULL)
            return NULL;
    
        // Then data layer, freeing vector layer if fail.
    
        vector->data = malloc(sz * sizeof (double));
        if (vector->data == NULL) {
            free(vector);
            return NULL;
        }
    
        // Here, both layers worked. Set size and return.
    
        vector->size = sz;
        return vector;
    }
    
    void delVector(struct Vector *vector) {
        // Can safely assume vector is NULL or fully built.
    
        if (vector != NULL) {
            free(vector->data);
            free(vector);
        }
    }
    

    By encapsulating the vector management like that, you ensure that vectors are either fully built or not built at all – there’s no chance of them being half-built.

    It also allows you to totally change the underlying data structures in future without affecting clients. For example:

    • if you wanted to make them sparse arrays to trade off space for speed.
    • if you wanted the data saved to persistent storage whenever changed.
    • if you wished to ensure all vector elements were initialised to zero.
    • if you wanted to separate the vector size from the vector capacity for efficiency(1).

    You could also add more functionality such as safely setting or getting vector values (see commented code in the header), as the need arises.

    For example, you could (as one option) silently ignore setting values outside the valid range and return zero if getting those values. Or you could raise an error of some description, or attempt to automatically expand the vector under the covers(1).


    In terms of using the vectors, a simple example is something like the following (very basic) main.c

    #include "vector.h"
    
    #include <stdio.h>
    
    int main(void) {
        Vector myvec = newVector(42);
        myvec.data[0] = 2.718281828459;
        delVector(myvec);
    }
    

    (1) That potential for an expandable vector bears further explanation.

    Many vector implementations separate capacity from size. The former is how many elements you can use before a re-allocation is needed, the latter is the actual vector size (always <= the capacity).

    When expanding, you want to generally expand in such a way that you’re not doing it a lot, since it can be an expensive operation. For example, you could add 5% more than was strictly necessary so that, in a loop continuously adding one element, it doesn’t have to re-allocate for every single item.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose we want two constructors for a class representing complex numbers: Complex (double re,
Suppose I want to define a set of functions, each having 4 overloads, the
This is my (maybe a little bit weird) thought, suppose I want to define
Suppose that we define an interface like this: interface Hashable { int hash(); }
Suppose I want to define an enum pointing to an array of objects. Can
Suppose I define a class A and I don't want anyone to write an
I want to define lifting with implicits. Suppose we have a function A =>
Suppose I have some macro #define NAME name , and I want to define
Suppose we have 2D vector of int like: 1 4 3 0 1 5
Suppose I want to add two buffers and store the result. Both buffers are

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.