logo
Tags down

shadow

C: strtok on pointer inside a struct


By : user3851512
Date : October 16 2020, 11:12 AM
I wish this helpful for you Note that strtok modifies the string - if your txt pointer is pointing at a read-only string (e.g. a const string literal) then you will get an exception.
code :


Share : facebook icon twitter icon

Improvements to dynamically allocate memory for a double pointer to struct inside a pointer to struct


By : user3544410
Date : March 29 2020, 07:55 AM
this one helps. The problem is product is a pointer to a pointer, so if you intended to only an array of product under Inventory, you must use -> notation instead of . notation for price. (See example 1 below) If however, you intended to actually nest an array of struct Product under each pointer-to-Product you allocate (i.e. subproducts), see example 2:
Note: after each allocation, you must check the return from malloc to insure the allocation succeeded. (omitted in example 1 below for brevity, shown in full in example 2)
code :
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int price;
} Product;

typedef struct {
    Product **product;
    int id;
} Inventory;

int main () {

    int i, j;
    int n1 = 2, n2 = 3;

    /* allocated / initiaize Inventory and Product */
    Inventory *inventory = malloc (n1 * sizeof *inventory);
    for (i = 0; i < n1; i++) 
    {
        inventory[i].id = i;
        inventory[i].product = malloc (n2 * sizeof *inventory[i].product);

        for (j = 0; j < n2; j++) 
        {
            inventory[i].product[j] = malloc (sizeof *inventory[i].product[j]);
            inventory[i].product[j]->price = (j + 1) * 2;
        }
    }

    /* print the inventory / procduct price */
    for (i = 0; i < n1; i++) 
    {
        printf ("\n product id : %d\n", inventory[i].id);
        for (j = 0; j < n2; j++) 
        {
            printf ("   price : %d\n", inventory[i].product[j]->price);
        }
    }

    /* free all memory */
    for (i = 0; i < n1; i++) 
    {
        for (j = 0; j < n2; j++) 
            free (inventory[i].product[j]);
        free (inventory[i].product);
    }
    free (inventory);

    return 0;
}
$ ./bin/allocate_ptr_in_struct

 product id : 0
   price : 2
   price : 4
   price : 6

 product id : 1
   price : 2
   price : 4
   price : 6
$ valgrind ./bin/allocate_ptr_in_struct
==10167== Memcheck, a memory error detector
==10167== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==10167== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==10167== Command: ./bin/allocate_ptr_in_struct
==10167==

 product id : 0
   price : 2
   price : 4
   price : 6

 product id : 1
   price : 2
   price : 4
   price : 6
==10167==
==10167== HEAP SUMMARY:
==10167==     in use at exit: 0 bytes in 0 blocks
==10167==   total heap usage: 9 allocs, 9 frees, 104 bytes allocated
==10167==
==10167== All heap blocks were freed -- no leaks are possible
==10167==
==10167== For counts of detected and suppressed errors, rerun with: -v
==10167== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int price;
} Product;

typedef struct {
    Product **product;
    int id;
} Inventory;

int main () {

    int i, j, k;
    int n1 = 2, n2 = 3, n3 = 2;

    /* allocated / initiaize Inventory and Product */
    Inventory *inventory = malloc (n1 * sizeof *inventory);
    if (!inventory) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        exit (EXIT_FAILURE);
    }
    for (i = 0; i < n1; i++) 
    {
        inventory[i].id = i;
        if (!(inventory[i].product = malloc (n2 * sizeof *inventory[i].product))) {
            fprintf (stderr, "error: virtual memory exhausted.\n");
            exit (EXIT_FAILURE);
        }

        for (j = 0; j < n2; j++) 
        {
            if (!(inventory[i].product[j] = malloc (n3 * sizeof *inventory[i].product[j]))) {
                fprintf (stderr, "error: virtual memory exhausted.\n");
                exit (EXIT_FAILURE);
            }
            for (k = 0; k < n3; k++)
                inventory[i].product[j][k].price = (j + 1) * 2 * (k + 1);
        }
    }

    /* print the inventory / procduct price */
    for (i = 0; i < n1; i++) 
    {
        printf ("\n  Inventory id : %d\n", inventory[i].id);
        for (j = 0; j < n2; j++) 
        {
            printf ("\n    Product[%d]\n", j);
            for (k = 0; k < n3; k++)
                printf ("      subproduct[%d][%d] price : %d\n", 
                        j, k, inventory[i].product[j][k].price);
        }
    }

    /* free all memory */
    for (i = 0; i < n1; i++) 
    {
        for (j = 0; j < n2; j++) 
            free (inventory[i].product[j]);
        free (inventory[i].product);
    }
    free (inventory);

    return 0;
}
$ ./bin/allocate_ptr_in_struct

  Inventory id : 0

    Product[0]
      subproduct[0][0] price : 2
      subproduct[0][1] price : 4

    Product[1]
      subproduct[1][0] price : 4
      subproduct[1][1] price : 8

    Product[2]
      subproduct[2][0] price : 6
      subproduct[2][1] price : 12

  Inventory id : 1

    Product[0]
      subproduct[0][0] price : 2
      subproduct[0][1] price : 4

    Product[1]
      subproduct[1][0] price : 4
      subproduct[1][1] price : 8

    Product[2]
      subproduct[2][0] price : 6
      subproduct[2][1] price : 12
$ valgrind ./bin/allocate_ptr_in_struct
==23024== Memcheck, a memory error detector
==23024== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==23024== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==23024== Command: ./bin/allocate_ptr_in_struct
==23024==

  Inventory id : 0

    Product[0]
      subproduct[0][0] price : 2
      subproduct[0][1] price : 4

    Product[1]
      subproduct[1][0] price : 4
      subproduct[1][1] price : 8

    Product[2]
      subproduct[2][0] price : 6
      subproduct[2][1] price : 12

  Inventory id : 1

    Product[0]
      subproduct[0][0] price : 2
      subproduct[0][1] price : 4

    Product[1]
      subproduct[1][0] price : 4
      subproduct[1][1] price : 8

    Product[2]
      subproduct[2][0] price : 6
      subproduct[2][1] price : 12
==23024==
==23024== HEAP SUMMARY:
==23024==     in use at exit: 0 bytes in 0 blocks
==23024==   total heap usage: 9 allocs, 9 frees, 128 bytes allocated
==23024==
==23024== All heap blocks were freed -- no leaks are possible
==23024==
==23024== For counts of detected and suppressed errors, rerun with: -v
==23024== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

How to store data from pointer returned by strtok into struct without it being lost?


By : Russ Tovar
Date : March 29 2020, 07:55 AM
I hope this helps you . In this example about the use of strdup, the program makes copies of the data obtained from strtok. The original string can then be freeed
The code posted has a mistake trying to assign a char* pointer to int*. In C, a textual number is not automatically converted to int.
code :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct Student{
    char *name;
    int  studentNumber;
} Student;

int main(void)
{
    char *string;
    char *tok;
    Student acolyte;

    // set up the input, like this to show use of `strdup` and `free`
    string = strdup("Tommy-1234567");       // allocate memory for source string
    if (string == NULL)                     // check it worked
        return 1;                           // failure

    // student name
    tok = strtok(string, "-");              // isolate first token
    if (tok == NULL)                        // check it worked
        return 1;                           // failure
    acolyte.name = strdup(tok);             // allocated mem for substring and copy
    if (acolyte.name == NULL)               // check it worked
        return 1;                           // failure

    // student number
    tok = strtok(NULL, "-");                // isolate next token
    if (tok == NULL)                        // check it worked
        return 1;                           // failure
    if (sscanf(tok, "%d", &acolyte.studentNumber) != 1)     // extract int
        return 1;                           // failure

    free(string);                           // can now get rid of source data

    // show result
    printf("Name: %s\n", acolyte.name);
    printf("Number: %d\n", acolyte.studentNumber);
    free(acolyte.name);                     // free the memory in struct
    return 0;
}
Name: Tommy
Number: 1234567

Accessing elements within a pointer of a struct inside another pointer to a struct


By : Shawn Ironmonger
Date : March 29 2020, 07:55 AM
I hope this helps . For starters C and C++ are different languages.
In any case you have to allocate the structures before accessing their elements throw pointers. Otherwise using uninitialized pointers or pointers that do not point to valid structures' objects results in undefined behavior of the program.
code :
#include <stdlib.h>
#include <stdio.h>

typedef struct
{
  unsigned int            a;
  unsigned int            b;
  unsigned int            c;
} inner;

typedef struct
{
  unsigned int            d;
  unsigned int            e;
  inner * in;
} outer;


int main( void ) 
{
    outer *out = malloc( sizeof( outer ) );

    if ( ( out != NULL ) && ( out->in = malloc( sizeof( inner ) ) ) )
    {
        out->in->a = 1;
        out->in->b = 2;
        out->in->c = 3;

        printf( "out->in = { a = %d, b = %d, c = %d }\n", out->in->a, out->in->b, out->in->c );

        free( out->in );
        free( out );
    }

    return 0;
}
out->in = { a = 1, b = 2, c = 3 }
#include <iostream>

typedef struct
{
  unsigned int            a;
  unsigned int            b;
  unsigned int            c;
} inner;

typedef struct
{
  unsigned int            d;
  unsigned int            e;
  inner * in;
} outer;

int main() 
{
    outer *out = new outer;

    out->in = new inner;

    out->in->a = 1;
    out->in->b = 2;
    out->in->c = 3;

    std::cout << "out->in = { a = " << out->in->a
              << ", b = " << out->in->b
              << ", c = " << out->in->c
              << " }" << std::endl;

    delete out->in;
    delete out;

    return 0;
}
void test(outer *out)
{
  //Update the value of out->in->a.
  out->in->a = 5;
}

How to free and write to NULL a pointer in an array inside a struct, indirectly via pointer to struct?


By : Soufin Rahimeen
Date : March 29 2020, 07:55 AM
around this issue Allow me to phrase your goal in my words
(after verifying my understanding in chat):
code :
void deleteP(FS *fs){
    Elem **el; // pointer to pointer, instead of pointer (and no calloc)
    el = &(fs->child[20]); // pointer to array member
    free(*el); // free the pointer in the array member (not a copy of it),
               // though the effect is the same
    *el = NULL; // write NULL to the array member, not a copy of it,
                // this is what changes the effect to what you want 
}

How to access struct field which is a pointer inside of a struct which is itself a pointer


By : LadiiSota
Date : March 29 2020, 07:55 AM
seems to work fine Yes I think it will automatically dereference. See https://golang.org/ref/spec#Selectors
I think rule number 3 is the one you're looking for:
Related Posts Related Posts :
  • Static / global variables in shared library in C language
  • Is there a tool to list global variables used and output by a C function?
  • functions returning char pointer
  • How many elements are full in a C array
  • Resources for writing kernel in C
  • OpenGL: How do I avoid rounding errors when specifying UV co-ordinates
  • Basic skeleton for a C OpenGL program on OSX
  • Float versus integer data type calculation issues in C
  • What have you used sysv/posix message queues for?
  • Recursive harmonic function returns NaN
  • How to fix "unable to open stdio.h in Turbo C" error?
  • C programming structure passed as cast to char *?
  • Do I need to #include <omp.h> in my C/C++ sources?
  • Find original owning process of a Linux socket
  • How can I send e-mail in C?
  • How is the lagged fibonacci generator random?
  • Trouble with dangling pointers and character arrays in C
  • Trying to compile with cl.exe
  • C code compilation failure
  • Gtk Draw Bitmap
  • booting from a disk/cd/usb
  • Due to Shared memory, when MS Visual C 6.0 DLL crashes it also causes VB 6 EXE to crash
  • Error receiving in UDP: Connection refused
  • How to get the port number from addrinfo in unix c
  • Should I declare the expected size of an array passed as function argument?
  • Is it possible to read in a string of unknown size in C, without having to put it in a pre-allocated fixed length buffer
  • How to use pcap_breakloop?
  • C Programming linux , read system inputs like ping or ls -l
  • Unsigned Short to Unsigned Long assignment
  • How to put bits into a character Array
  • C moving the cursor to the beginning of the current line
  • libgtk version issue on ubuntu
  • creating a list of queues
  • Pointer to a specific fixed address
  • How to parse HTTP responses in C?
  • Use strtol or strtok to parse a string in C?
  • fread/fwrite string in C
  • c - random number generator
  • input-output in C
  • c - output to file
  • Reserve RAM in C
  • ncurses transparent console background
  • Faster math library than glibc on x86_64/linux?
  • For buffer overflows, what is the stack address when using pthreads?
  • I want to use Google Translate as part of some C code
  • Sort Hash Tables Glib - qsort
  • Is the next C standard actively developed?
  • Inserting into a Binary Tree which uses void* in C
  • c - fork() code
  • C .pc file warning
  • C warning Missing sentinel in function call
  • Getting printf() to drop the trailing ".0" of values
  • size of struct - size_t in c
  • Finding dimensions of a 2D array in C using pointers
  • C memset warning
  • Burning a CD programmatically
  • How to programatically convert a time from one timezone to another in C?
  • Need help implementing simple socket server using GIOService (GLib, Glib-GIO)
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org