![](/img/trans.png)
[英]Why does this printf statement, or lack there of, alter the effect of the for loop?
[英]Why does a printf statement in a for loop seem to depend on an unrelated previous printf outside that loop?
我在 C 中玩耍,以實現“Eratosthenes 篩法”來尋找素數。 我想出了以下代碼:
#include <stdio.h>
#include <stdlib.h>
void strike_multiples(int n, int *storage); // Function prototype
int ceiling = 500; // Maximum integer up to which primes are found
int main(void) {
int *ptr = malloc(sizeof(int) * ceiling); // Create buffer in memory
int no_of_primes_found = 0;
printf("Print anything\n");
for (int i = 0; i < ceiling; i++) { // Initialise all elements in buffer to zero
*(ptr + i * sizeof(int)) = 0;
}
for (int j = 2; j < (ceiling / 2) + 1; j++) {
if (*(ptr + j * sizeof(int)) == 0) {
strike_multiples(j, ptr);
}
}
for (int k = 2; k < ceiling; k++) {
if (*(ptr + sizeof(int) * k) == 0) {
no_of_primes_found++;
printf("%i\n", k);
}
}
printf("%i primes found\n", no_of_primes_found);
free(ptr);
return 0;
}
void strike_multiples(int n, int *storage) { // This function strikes all multiples of a given integer within the range
for (int i = 2; i < (ceiling / n) + 1; i++) { // (striking means setting the value of the corresponding index in the allocated memory to one)
*(storage + sizeof(int) * n * i) = 1;
}
}
這編譯得很好,確實會給我最多 500 個素數(最后一個是 499)。 但最奇怪的是行printf("Print anything\n");
. 它似乎沒有做任何與功能相關的事情。 但是,如果我刪除此行或將其注釋掉,我將不會收到任何 output。似乎printf("%i\n", k);
第三個 for 循環中的行依賴於之前發生的一些其他打印。
這里發生了什么? 為什么在 for 循環之前進行一些 -任何- 打印會對循環中已識別素數的完全不相關的打印產生影響?
程序中 for 循環中的此類表達式如下所示
*(ptr + i * sizeof(int)) = 0;
不正確並導致未定義的行為。
相反,你需要寫
*(ptr + i) = 0;
這個表達式等同於
ptr[i] = 0;
來自 C 標准(6.5.2.1 數組下標)
2 后綴表達式后跟方括號[]中的表達式是數組object中元素的下標指定。下標運算符[]的定義是E1[E2]等同於(*((E1)+( E2)))。 由於適用於二元 + 運算符的轉換規則,如果 E1 是數組 object(等效於指向數組對象的初始元素的指針)並且 E2 是 integer,則 E1[E2] 指定的第 E2 個元素E1(從零開始計數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.