簡體   English   中英

在使用指針添加C ++數組時需要一些建議

[英]Need some advice with C++ array addition using pointers

我正在嘗試使用指針獲取兩個數組的和,但是當輸出全部為零時,我該怎么辦?

如果有更好的方法,請問我想知道

這是代碼

更新

#include  < cstdio >  
#include < iostream >

using namespace std;

unsigned i;

int main(){

/* Array`s input */

    short A[3];

    for( i = 0 ; i < 3 ; i++ ){

    printf("Insert number for [A]: ");
    scanf("%hd",&A[i]);

    }

    printf("\n");

    short B[3];

    for( i = 0 ; i < 3 ; i++ ){

    printf("Insert number for [B]: ");
    scanf("%hd",&B[i]);

    }

    short C[3];

// Pointers

    short *punt_A, *punt_B, *punt_C;

    punt_A = &A[0];
    punt_B = &B[0];
    punt_C = &C[0];

// Addition

    for( i = 0 ; i < 3 ; i++ ){

    C[i]=punt_A[i]+punt_B[i];

    }

    printf("\n\nArray addition = { %d, %d, %d }\n", *punt_C, *(punt_C + 1), *(punt_C + 2));



return 0;

}

記住short A[3]; 將允許您合法訪問A [0] .. A [2]

for( i = 3; i-- ; )
{
/* i-- is a tricky way of entering the loop
 * This checks i for the condition, and passes (i-1, the current value
 * of i) to the loop
 * Though the method is smart I think it is less readable
 * There is no access violation here, forgive my previous comment :(
 */
printf("Insert number for [A]: ");
scanf("%hd",&A[i]);  // Remember %hd for short.

}

此處的加法可能更好地表示為:

for( i = 0; i<3;i++){ 
/* I changed the forloop structure which may be used 
 * for reading the arrays too. In fact this has no surprises.
 */
C[i]=punt_A[i]+punt_B[i]; // Or *(punt_A+i) + *(punt_B+i)

}

關於,

printf("\n\nArray addition = { %d, %d, %d }\n", *punt_A, *punt_B, *punt_C );

這僅分別打印A[0],B[0],C[0]並且格式說明符“%d”與short類型不匹配。 正確的說明符是“%hd”。 使用循環打印結果數組。

punt_Apunt_Bpunt_C均指向其各自數組末尾的一個元素,例如, punt_A現在指向A[3] 數組沿單詞邊界分配在堆棧上,因此堆棧上的每個數組后面都有“死區”。 在Windows調試版本中,未初始化的區域標記有0xcccccccc所以我看到-13108是(short)(0xcccccccc) 在發行版本中,您只看到該內存地址中以前留下的所有內容,在許多情況下,該內容僅為零。

當我看到for (i = 3; i--; )時,我做了兩次。 您已將i--檢查條件正常運行的地方。 for (i = 2; i >= 0; i--; )更清楚。 它實際上確實是偶然地工作的,因為在評估條件i--時,它將采用i並檢查該條件是否為非零。 檢查后, i遞減並進入循環。 i變為零時,循環終止。 因此,在循環內您將看到i = 2、1、0。在任何求值之后,例如int n = 1; ,將應用后減運算符int n = 1; 然后n + n--; 返回2,而不是1。對表達式求值后, n遞減。

幾件事:

  • 您的數組和指針被聲明為short ,但是scanf() / printf()說明符為%d ,這意味着int 通常, short是16位整數, int是32位整數。 那會導致怪異的效果。
  • 您應該從2而不是3開始循環。 3已經超出范圍。
  • 在最后一個循環的末尾,所有指針都將指向數組的末尾,但是無論如何您都將它們傳遞給printf() (這實際上是未定義的行為)。
  • 實際上,您是否不想輸出C[]的內容-加法結果? 為什么在那里使用punt_Apunt_B

現在這是您程序的粗略解決方案

#include <stdio.h>
#include <iostream>

using namespace std;

unsigned i;

int main(){


/* Array`s inputs */

    int *A = new int[3];

    for( i = 3 ; i-- ; ){

        cout << "Insert number for [A]: " << endl;
        scanf("%d",&A[i]);
    }

    printf("\n");

    int* B = new int[3];

    for( i = 3; i-- ; ){

    cout << "Insert number for [B]: " << endl;
    scanf("%d",&B[i]);

    }

    int* C = new int[3];

// Pointers

    int *punt_A, *punt_B, *punt_C;

    punt_A = A;
    punt_B = B;
    punt_C = C;

// Addition

    for( i = 3; i--; ){

    *punt_C = *punt_A + *punt_B;
    punt_A++;
    punt_B++;
    punt_C++;

    }

    for(int i = 0; i < 3; i++)
    {
        cout << *C << endl;
        C++;
    }

delete [] A;
delete [] B;
delete [] C;
return 0;
}
  • 在您的程序中:

問題是:您初始化短褲數組。 short的大小為2個字節。 但是,您正在加載數字,期望整數%d至4個字節。 因此,您加載了2個字節,而其他兩個字節只是被忽略了。 我在沒有-Wall -pedantic標志的情況下對其進行了編譯,但仍收到警告:

main.cpp: In function ‘int main()’:
main.cpp:17:21: warning: format ‘%d’ expects argument of type ‘int*’, but argument 2 has type ‘short int*’ [-Wformat=]
     scanf("%d",&A[i]);
                     ^
main.cpp:28:21: warning: format ‘%d’ expects argument of type ‘int*’, but argument 2 has type ‘short int*’ [-Wformat=]
     scanf("%d",&B[i]);

現在解決此問題,使它們全部為整數。 但是您要求更好的解決方案。 如果給了兩個數組,並且必須將它們求和,並且由於您使用的是c ++ 11,那么使用容器可能會更容易。

# include <stdio.h>
# include <iostream>

#include <vector>

#define COUNT 3

using namespace std;

unsigned i;

int main()
{
/* Array`s inputs */

    vector<int> A, B;

    int worker;

    for( i = COUNT ; i-- ; )
    {
        cout << "Insert number for [A]: " << endl;

        cin >> worker;
        A.push_back(worker);
    }

    for( i = COUNT ; i-- ; )
    {
        cout << "Insert number for [B]: " << endl;

        cin >> worker;
        B.push_back(worker);
    }

    for(int i = 0; i < COUNT; i++)
    {
        A[i] = A[i] + B[i];
    }
    cout << "summed up" << endl;

    for(vector<int>::iterator it = A.begin(); it != A.end(); it++)
    {
        cout << *it << endl;
    }
return 0;
}

現在注意,我為您的數量定義了一個定義。 而且,我再次使用aray A進行輸出,從而節省了空間。 問題在於,向量本身具有push_back()的O(n)復雜度(除非您減小大小,但是需要知道確切的輸入數,否則將來可能不會出現,您可能要等到EOF才加載)。 為了消除這種情況並使程序更快,可以使用列表以獲得更好的性能。

但是,如果您想使用指針,請使用迭代器。 :]

(請注意,我的代碼未得到保護,這意味着如果您寫了一封信,它會做奇怪的事情,但我概述了這個想法:]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM