繁体   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