Note that there are some explanatory texts on larger screens.

plurals
  1. POString manipulation & memory allocation - C
    primarykey
    data
    text
    <p>I am in the process of learning C. I have a method that takes 3 strings and combines them to do some operation. Following was my first implementation using a GCC compiler. </p> <pre><code>void foo(const char *p1, const char *p2, const char *p3) { size_t length = strlen(p1) + strlen(p2) + strlen(p3); char combined[length + 1]; memset(combined, 0, length + 1); strcat(combined, p1); strcat(combined, p2); strcat(combined, p3); printf("Result : %s", combined); } int main() { foo("hello ", "world ", "how"); return 0; } </code></pre> <p>This works well. But when I compiled this using, <code>cc -Wall -pedantic -g foo.c -o foo</code>, I started getting warnings like <code>ISO C90 forbids variable length array ‘combined’</code>. MSVC was not compiling this code. Changed the code like</p> <pre><code>void foo(const char *p1, const char *p2, const char *p3) { size_t length = strlen(p1) + strlen(p2) + strlen(p3); char *combined = (char *) malloc(length + 1); memset(combined, 0, length + 1); strcat(combined, p1); strcat(combined, p2); strcat(combined, p3); printf("Result : %s", combined); free(combined); } </code></pre> <p><strong>Questions</strong></p> <ol> <li>Is this the correct implementation? </li> <li>If variable length arrays are not part of standard, why GCC implemented it? If the code is expected to compile only on GCC, using variable arrays will be a better alternative than using malloc? </li> <li>I think the thumb rule is, if memory required is knows at compile time, use arrays else use malloc to allocate required memory. Is this correct?</li> <li>My code is expected to compile on GCC and MSVC. I will be developing on GCC usually. So what are the compiler flags that ensures maximum portability? Currently I am using <code>-Wall -pedantic</code>. Should I use <code>-ansi</code> too? What would be the equivalent flags available in MSVC?</li> <li>What are the other common things to consider when writing portable C code?</li> </ol>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload