Can it be made simpler or more efficient?

I am trying to convert some code from a dynamically typed language to C. Please bear with me since I have no practical experience with C.

I have a dispatch function that decides how to convert it based on the value of the flag argument.

void output_dispatcher(char *str, int strlen, int flag) {
    char output[501];
    char *result;

    switch (flag) {
        /* No conversion */
        case 0:
            result = str;
            break;
        case 1:
            result = convert_type1(output, str, strlen);
            len = strlen(result);
            break;
        /* ... */
    }
    /* do something with result */
}

I currently have 5 different output converters, and all of them (even the future) guarantee only 300-500 characters. From my reading, it is preferable to use a heap variable than dynamically allocate space on the stack, if possible. A function declaration for one is as follows:

static char * convert_type1(char *out, const char *in, int inlen);

strlen , , , . , , , ? , " ".

void output_dispatcher(char *str, int strlen, int flag) {
    char output[501];

    switch (flag) {
        /* No conversion */
        case 0:
            output = str;  /* ERROR: incompatible type */
            break;
        case 1:
            strlen = convert_type1(output, str, strlen);
            break;
        /* ... */
    }
    /* do something with result */
}

, ?

+3
5

, , :

static char * convert_type1(char *out, const char *in, int *len);

:

result = convert_type1(output, str, &strlen);

, , .

, , , , .

+1

:

output = str;

, , , .

"output" - , .

str = output;

, char ptr .

, "output" - , .

, :

char output[501];
char output1[501];

:

output1 = output;

, C output1.

, ptrs.

0

char [501]; output = str;/* : */

= >

strncpy (output, str, sizeof (output));

, , 'output', 'str'

0

. output - , char, str - . , str , ? , , , str . str, .

0

C - . , , str output, :

strcpy(output, str);

, ,

memcpy(output, str, strlen + 1);

( , , strlen < sizeof output).

Note that the name of a local variable strlen, thereby obscuring the standard function of that name, will be more than a little confusing for those who look at your code later. I would choose a different name.

0
source

Source: https://habr.com/ru/post/1777276/


All Articles