Issues creating a library with char arrays

You are creating temporary object inside this function and returning a pointer to it which will point to random piece of memory once function is returned as temp object gets destroyed

also you don’t need to ifndef included libraries they all should have include guards already,

following code produced

process_data: init_answer=Yes=25=75=50=2.5=6.5
  0:       0  init_answer
  1:       0  Yes
  2:      25  25
  3:      75  75
  4:      50  50
  5:       2  2.5
  6:       6  6.5
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_TOKS   10
char * toks [MAX_TOKS];
int    vals [MAX_TOKS];

int
process_data(
    char *s )
{
    int  i = 0;

    printf ("%s: %s\n", __func__, s);

    for (toks [i] = strtok (s, "="); toks [i]; )  {
        vals [i] = atoi (toks [i]);
        toks [++i] = strtok (NULL, "=");
    }

    return i;
}

int
getMsg (
    char *buf,
    int   size )
{
    snprintf (buf, size-1, "init_answer=Yes=25=75=50=2.5=6.5");
    return strlen (buf);
}

int
main ()
{
    char s [100];

    getMsg(s, sizeof(s));
    int n = process_data (s);

    for (int i = 0; i < n; i++)  {
        printf ("  %d:  %6d  %s\n", i, vals [i], toks [i]);
    }
}

one issue with using less than familiar coding (e.g. template) is that it makes if more difficult for others to read or if it's a less than familiar approach to doing things (i.e. conventional style.

of course there are good reasons when it significantly reduces the size of the code and yes, it's a learning opportunity for the reviewer.

i was told of a comment in some code that was simply "think about it". i believe the (assembly) code was self modifying (a branch instruction).

why make it harder to read the code

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.