Note that there are some explanatory texts on larger screens.

plurals
  1. POC pointers inconsistency
    text
    copied!<p>I'm working on a program for a C class and I reached a point where I don't know what to do. We are implementing a String library type.</p> <p>I have my header file (MyString.h)</p> <pre><code>typedef struct { char *buffer; int length; int maxLength; } String; String *newString(const char *str); </code></pre> <p>The file implementing the functions (MyString.c)</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include "MyString.h" String *newString(const char *str) { // Allocate memory for the String String *newStr = (String*)malloc(sizeof(String)); if (newStr == NULL) { printf("ERROR: Out of memory\n"); return NULL; } // Count the number of characters int count; for (count = 0; *(str + count) != '\0'; count++); count++; // Allocate memory for the buffer newStr-&gt;buffer = (char*)malloc(count * sizeof(char)); if (newStr-&gt;buffer == NULL) { printf("ERROR: Out of memory\n"); return NULL; } // Copy into the buffer while (*str != '\0') *(newStr-&gt;buffer++) = *(str++); *(++newStr-&gt;buffer) = '\0'; // Set the length and maximum length newStr-&gt;length = count; newStr-&gt;maxLength = count; printf("newStr-&gt;buffer: %p\n",newStr-&gt;buffer); // For testing purposes return newStr; } </code></pre> <p>And a tester (main.c)</p> <pre><code>#include &lt;stdio.h&gt; #include "MyString.h" main() { char str[] = "Test character array"; String *testString = newString(str); printf("testString-&gt;buffer: %p\n",testString-&gt;buffer); // Testing only } </code></pre> <p>The problem is that, even though testString is pointing to the String created in newString(), their buffers point to different memory addresses. Why is that?</p> <p>Thanks in advance</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