Thread: Need to allocate memory for structures in a cycle, having array of pointers to them

  1. #1
    Registered User
    Join Date
    May 2020
    Posts
    3

    Need to allocate memory for structures in a cycle, having array of pointers to them

    Need to allocate memory for structures, having array of pointers to them using pointer arithmetic. Is it possible?

    Code:
    pointer_to_str_type *p = malloc(10 * sizeof(pointer_to_structure_type));
    
    
    for(int i=0;i<10;i++){
    
       p+i = malloc(sizeof(str)); // error: left side must be lvalue
       p[i] = malloc(sizeof(str)); // ok
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,286
    Sure is.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct {
      int bar;
    } foo_st;
    
    int main ( ) {
      // make f0[10]
      foo_st *f0 = malloc(10*sizeof(*f0));
    
      // make f1[10][10]
      foo_st **f1 = malloc(10*sizeof(*f1));
      for(int i = 0 ; i < 10 ; i++ ) {
        f1[i] = malloc(sizeof(*f1[i]));
      }
    
      // free them
      free(f0);
    
      for(int i = 0 ; i < 10 ; i++ )
        free(f1[i]);
      free(f1);
    }
    Oh, and avoid creating typedef's for 'pointer to structure' types in an attempt to try and hide a single *.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to allocate memory for an array of strings?
    By rassul in forum C Programming
    Replies: 7
    Last Post: 11-16-2015, 08:13 AM
  2. Replies: 6
    Last Post: 04-02-2012, 07:38 PM
  3. Allocate memory for an Array
    By Coding in forum C++ Programming
    Replies: 3
    Last Post: 01-05-2008, 06:18 PM
  4. Replies: 2
    Last Post: 05-10-2005, 07:15 AM
  5. How to allocate memory in multidimensional array?
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 10-15-2001, 10:07 AM

Tags for this Thread