這是一個在運行時從用戶那里獲取輸入并根據輸入的引數列印 hello world 的程式。用戶可以列印 2 hello world。然而,第三個 hello world 是有條件的,取決于是否輸入了 c 值。
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, char *argv[])
{
unsigned int a, b, c;
a = strtoul(argv[1], 0, 0);
b = strtoul(argv[2], 0, 0);
c = strtoul(argv[3], 0, 0);
int *p= NULL;//initialize the pointer as null.
printf("\n first no %d \n ", a);
printf("\n second no %d \n ", b);
if ( c == *p)
{
printf("\n third no %d \n ", c);
}
return 0;
}
- 假設我將程式運行為 ./hello 1 2 -> 這將列印“hello world 1”“hello world 2”。
- 如果我將程式運行為 ./hello 1 2 3 -> 這將列印“hello world 1”“hello world 2”“hello world 3”。
- 如何更正我的程式以獲得預期的效果?
uj5u.com熱心網友回復:
argc函式的第一個引數main表示傳遞給程式的引數數量,因此您可以檢查 的值argc以確定程式的行為。
(例如,如果您將程式運行為,則./hello 2 7 1 8的值為。)argc5
#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i)
{
printf("hello world %s\n", argv[i]);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439022.html
上一篇:當我宣告這個字符指標陣列時,記憶體是如何組織的?“字符*運算[30]”
下一篇:我如何解釋以下代碼行
