{"id":4758,"date":"2021-05-22T00:01:58","date_gmt":"2021-05-22T07:01:58","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=4758"},"modified":"2021-05-15T11:25:36","modified_gmt":"2021-05-15T18:25:36","slug":"creating-an-array-of-pointers-correct","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=4758","title":{"rendered":"Creating a Pointer Array (Correct)"},"content":{"rendered":"<p>Unlike the iffy issue with assigning a pointer directly to a string, you cannot declare a pointer and assign it an immediate value. This puzzle was presented in <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4753\">last week&#8217;s Lesson<\/a>. No, to do things properly requires not a single statement but three separate steps.<br \/>\n<!--more--><br \/>\nThese steps are:<\/p>\n<p>1. Declare the pointer<br \/>\n2. Allocate storage<br \/>\n3. Assign values<\/p>\n<p>Declaring the pointer is done like any other variable, though at this point in the code it&#8217;s uninitialized:<\/p>\n<p><code>int *nums;<\/code><\/p>\n<p>The pointer could be initialized at declaration, providing the above statement (or similar) is set in the code <em>after<\/em> another variable or memory location is established. Still, being a traditionalist, I place my variable declarations at the start of the code, well before any action.<\/p>\n<p>The second step is to allocate storage. For this job, I use the <em>malloc()<\/em> function to create a chunk of memory adequate to store the data. From last week&#8217;s example, the data consists of three <em>int<\/em> values:<\/p>\n<p><code>nums = (int *)malloc( sizeof(int) * 3 );<br \/>\nif( nums==NULL )<br \/>\n{<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;fprintf(stderr,\"Memory allocation error\\n\");<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;exit(1);<br \/>\n}<\/code><\/p>\n<p>The <em>malloc()<\/em> function is typecast to an <em>int<\/em> pointer. Its allocation consists of a memory chunk equal to the size of an integer multiplied by three: <code>sizeof(int) * 3<\/code>. The address is assigned to the <code>nums<\/code> pointer, which is immediately tested against the <code>NULL<\/code> defined constant. A positive test means the allocation failed, and the code responds appropriately.<\/p>\n<p>After creating the pointer and assigning it an appropriately-sized chunk of memory, values are assigned:<\/p>\n<p><code>for( x=0; x<3; x++ )<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;*(nums+x) = x+1;<\/code><\/p>\n<p>The <em>for<\/em> loop steps thrice, each time assigning an offset within the memory buffer (referenced by <code>nums<\/code>) to the value <code>x+1<\/code>.<\/p>\n<p>Here is the full code:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2021_05_22-Lesson.c\" rel=\"noopener\" target=\"_blank\">2021_05_22-Lesson.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n\r\nint main()\r\n{\r\n    int *nums;\r\n    int x;\r\n\r\n    <span class=\"comments\">\/* allocate storage for 3 integers *\/<\/span>\r\n    nums = (int *)malloc( sizeof(int) * 3 );\r\n    if( nums==NULL )\r\n    {\r\n        fprintf(stderr,\"Memory allocation error\\n\");\r\n        exit(1);\r\n    }\r\n\r\n    <span class=\"comments\">\/* assign the integer values *\/<\/span>\r\n    for( x=0; x&lt;3; x++ )\r\n        *(nums+x) = x+1;\r\n\r\n    <span class=\"comments\">\/* output the results *\/<\/span>\r\n    printf(\"%d %d %d\\n\",\r\n            *(nums+0),\r\n            *(nums+1),\r\n            *(nums+2)\r\n          );\r\n\r\n    return(0);\r\n}<\/pre>\n<p>Granted, it would be easier if this expression worked:<\/p>\n<p><code>int *nums = { 1, 2, 3 };<\/code><\/p>\n<p>The problem is that the <code>{ 1, 2, 3 }<\/code> thing is a &#8220;scalar,&#8221; not an array; declaring it in the statement doesn&#8217;t allocate storage and set those values into memory. They must already exist in memory for declaration\/assignment to work. Or, as demonstrated in this post, the pointer must be declared, storage allocated, and then storage filled to properly perform the task.<\/p>\n<p><em>&#8220;But what about assigning a pointer to a string?&#8221;<\/em><\/p>\n<p>My guess is that the pointer string assignment works because the compiler allocates storage for strings declared in your source code:<\/p>\n<p><code>char *prompt = \"Type something: \";<\/code><\/p>\n<p>This declaration works because the compiler knows the string&#8217;s address when it&#8217;s set into memory. The pointer absorbs the memory location. But the problem with assigning a string thin this manner is that the location doesn&#8217;t behave the same as if the storage was allocated as demonstrated in this Lesson.<\/p>\n<p>So while this declaration is kosher:<\/p>\n<p><code>int nums[] = { 1, 2, 3 };<\/code><\/p>\n<p>This one is not:<\/p>\n<p><code>int *nums = { 1, 2, 3 };<\/code><\/p>\n<p>The compiler has no obligation to create the &#8220;scalar&#8221; and assign it an address. It seems like it would, but no.<\/p>\n<p>Regardless of my guesses, my point is that you cannot allocate a pointer to an array of values unless it&#8217;s a string. Even then, be wary when creating a pointer to a string as its behavior is inconsistent with more traditional and properly-created strings.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>It&#8217;s possible to assign a pointer to an array of integers, but you can&#8217;t do it all in a single statement. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4758\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-4758","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4758","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4758"}],"version-history":[{"count":7,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4758\/revisions"}],"predecessor-version":[{"id":4780,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4758\/revisions\/4780"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4758"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4758"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4758"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}