在這個程式中,我們需要使用指標運算來求陣列元素的和。
這裡我們使用 * 來表示儲存在記憶體位址處的值,而該位址將保留儲存在變數中。因此「int *ptr」表示ptr是一個變量,其中包含一個位址,該位址的內容是一個整數。
*p表示它是一個指標變數。使用它和 sum() 我們將找出陣列元素的總和。
<span class="com">#include</span><span class="pln"> </span><span class="str"><stdio.h></span> <span class="kwd">void</span><span class="pln"> s</span><span class="pun">(</span><span class="kwd">int</span><span class="pun">*</span><span class="pln"> a</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> len</span><span class="pun">) </span><span class="pun">{</span> <span class="kwd"> int</span><span class="pln"> i</span><span class="pun">,</span><span class="pln"> s_of_arr </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span> <span class="kwd"> for</span><span class="pln"> </span><span class="pun">(</span><span class="pln">i </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span><span class="pln"> i </span><span class="pun"><</span><span class="pln"> len</span><span class="pun">;</span><span class="pln"> i</span><span class="pun">++)</span> <span class="pln"> s_of_arr </span><span class="pun">=</span><span class="pln"> s_of_arr </span><span class="pun">+</span><span class="pln"> </span><span class="pun">*(</span><span class="pln">a </span><span class="pun">+</span><span class="pln"> i</span><span class="pun">);</span> <span class="pln"> printf</span><span class="pun">(</span><span class="pln"> </span><span class="str">"sum of array is = %d"</span><span class="pln"> </span><span class="pun">,</span><span class="pln">s_of_arr</span><span class="pun">);</span> <span class="pun">}</span> <span class="kwd">int</span><span class="pln"> main</span><span class="pun">() </span><span class="pun">{</span> <span class="kwd"> int</span><span class="pln"> arr</span><span class="pun">[]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">1</span><span class="pun">,</span><span class="lit">2</span><span class="pun">,</span><span class="lit">4</span><span class="pun">,</span><span class="lit">6</span><span class="pun">,</span><span class="lit">7</span><span class="pun">,-</span><span class="lit">5</span><span class="pun">,-</span><span class="lit">3</span><span class="pln"> </span><span class="pun">};</span> <span class="pln"> s</span><span class="pun">(</span><span class="pln">arr</span><span class="pun">,</span><span class="pln"> </span><span class="lit">7</span><span class="pun">);</span> <span class="kwd"> return</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span> <span class="pun">}</span>
Sum of array = 12
Begin Initialize array to hold the variables. Call function s to get the sum of the variables. Print the sum. End.
以上是在C語言中使用指標算術來計算陣列的總和的詳細內容。更多資訊請關注PHP中文網其他相關文章!