Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic Array malloc empties separate array
    text
    copied!<p>I am having an issue with dynamic arrays and <code>malloc</code>. I am fairly new to C so please excuse (and advise on) any rookie mistakes.</p> <p>The problem is I create an array (input_string in this case) and pass it to <code>func2</code>. Then in <code>func2</code> I do a test, print out the first element of input_string.</p> <p>This works as expected in the first printout before the <code>malloc</code>, but after the <code>malloc</code> it doesn't print anything. This seems weird to me since in between the to <code>printf</code> statements I do nothing to the input_string.</p> <p>I'm assuming that I am dealing with these arrays incorrectly, but I'm unsure.</p> <p>Here is a snippet of the code in question:</p> <p><strong>Updated</strong></p> <pre><code>... // includes not in snippet /* CONSTANTS */ #define LINE_LEN 80 /* Function declarations */ char* func1(void); char* func2(int tl, char* input_string); int main(void) { char* input_string; int tab_length; char* output_string; input_string = func1(); output_string = func2(tl, input_string); return 0; } char* func1(void) { char cur_char; char* input_ptr; char input_string[LINE_LEN]; while ((cur_char = getchar()) != '\n' &amp;&amp; chars_read &lt; 80) { // iterate and create the array here } input_ptr = &amp;input_string[0]; /* set pointer to address of 0th index */ return input_ptr; } char* func2(int tl, char* input_string) { int n = 0, output_idx = 0; char* output_ptr; printf("\nBefore malloc: %c ", *(input_string)); output_ptr = malloc(tab_length * chars_read+1); if (output_ptr == NULL) { printf("Failed to allocate memory for output_ptr.\nExiting"); exit(1); } printf("\nAfter malloc: %c ", *(input_string)); ... return output_ptr; } </code></pre> <p>P.s.: Any undeclared variables have been declared outside of this snippet of code.</p> <p><strong>Update</strong></p> <p>Thanks for all the replies and advice. It is very much appreciated.</p>
 

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