Dynamic string array structure in C

I need to write a function in c that will return a dynamic array of strings. Here are my requirements:

  • I have 10 different validation functions that will return either true or false and related error text. (the error text string is also dynamic).
  • My function should collect the result (true or false) + an error string, and it will be called n validation functions. Therefore, my function should collect n results and finally return a dynamic array of strings to other functions.
+3
source share
3 answers

You can select an array of arbitrary length with malloc () (it looks like a “new” in Java) and make it grow or shrink with realloc ().

, free(), C, .

: http://www.gnu.org/software/libc/manual/html_node/Memory-Allocation.html#Memory-Allocation

Edit:

#include <stdlib.h>
#include <string.h>
int main(){
    char * string;
    // Lets say we have a initial string of 8 chars
    string = malloc(sizeof(char) * 9); // Nine because we need 8 chars plus one \0 to terminate the string
    strcpy(string, "12345678");

    // Now we need to expand the string to 10 chars (plus one for \0)
    string = realloc(string, sizeof(char) * 11);
    // you can check if string is different of NULL...

    // Now we append some chars
    strcat(string, "90");

    // ...

    // at some point you need to free the memory if you don't want a memory leak
    free(string);

    // ...
    return 0;
}

2: ( )

#include <stdlib.h>
int main(){
    // Array of strings
    char ** messages;
    char * pointer_to_string_0 = "Hello";
    char * pointer_to_string_1 = "World";
    unsigned size = 0;

    // Initial size one
    messages = malloc(sizeof(char *)); // Note I allocate space for 1 pointer to char
    size = 1;

    // ...
    messages[0] = pointer_to_string_0;


    // We expand to contain 2 strings (2 pointers really)
    size++;
    messages = realloc(messages, sizeof(char *) * size);
    messages[1] = pointer_to_string_1;

    // ...
    free(messages);

    // ...
    return 0;
}
+1

, . , , sn .

0
  • examine() , ? ( validate())

  • , 10 examine() , , 10 / validate()?

Java C, , , :

  • Array.length C: .

  • C "": / , ,

  • , C , struct, typedef , - -/ C...

  • , : , / Java- C, , / // , ( , , structs/study, , , , )

;)

0

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


All Articles