简体   繁体   English

在使用指针添加C ++数组时需要一些建议

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

I`m trying to get the sum of two arrays using pointers, but when the output comes all are zeros, what can I do? 我正在尝试使用指针获取两个数组的和,但是当输出全部为零时,我该怎么办?

And please if there a better way to do it I would like to know 如果有更好的方法,请问我想知道

Here`s the code 这是代码

UPDATE 更新

#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;

}

Remember short A[3]; 记住short A[3]; will allow you to legally access A[0]..A[2] 将允许您合法访问A [0] .. A [2]

In

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.

}

Addition here may be better represented as : 此处的加法可能更好地表示为:

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)

}

Regarding, 关于,

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

This prints only A[0],B[0],C[0] respectively and your format specifier "%d" doesn't match the type short. 这仅分别打印A[0],B[0],C[0]并且格式说明符“%d”与short类型不匹配。 The right specifier is "%hd". 正确的说明符是“%hd”。 Print the result array using a loop. 使用循环打印结果数组。

punt_A , punt_B , punt_C are all left pointing one element past the end of their respective arrays, eg punt_A is now pointing at A[3] . punt_Apunt_Bpunt_C均指向其各自数组末尾的一个元素,例如, punt_A现在指向A[3] The arrays are allocated on the stack along word boundaries, so there is "dead space" after each array on the stack. 数组沿单词边界分配在堆栈上,因此堆栈上的每个数组后面都有“死区”。 In a Windows debug build, uninitialised areas are marked with 0xcccccccc so I see -13108 which is (short)(0xcccccccc) . 在Windows调试版本中,未初始化的区域标记有0xcccccccc所以我看到-13108是(short)(0xcccccccc) In a release build, you just see whatever was left in that memory address from before, which in many cases is just zero. 在发行版本中,您只看到该内存地址中以前留下的所有内容,在许多情况下,该内容仅为零。

I did a double take when I saw for (i = 3; i--; ) . 当我看到for (i = 3; i--; )时,我做了两次。 You've put i-- where the check condition normally goes. 您已将i--检查条件正常运行的地方。 It's clearer to use for (i = 2; i >= 0; i--; ) . for (i = 2; i >= 0; i--; )更清楚。 It does actually work by accident because when the condition i-- is evaluated, it takes the i and checks whether that condition is nonzero. 它实际上确实是偶然地工作的,因为在评估条件i--时,它将采用i并检查该条件是否为非零。 After the check, i gets decremented and enters the loop. 检查后, i递减并进入循环。 When i becomes zero, the loop terminates. i变为零时,循环终止。 So inside the loop you see i = 2, 1, 0. The post-decrement operator is applied after any evaluations, eg, if int n = 1; 因此,在循环内您将看到i = 2、1、0。在任何求值之后,例如int n = 1; ,将应用后减运算符int n = 1; then n + n--; 然后n + n--; returns 2, not 1. n is decremented after the expression is evaluated. 返回2,而不是1。对表达式求值后, n递减。

Several things: 几件事:

  • Your arrays and pointers are declared as short , but scanf() / printf() specifiers are %d , which mean int . 您的数组和指针被声明为short ,但是scanf() / printf()说明符为%d ,这意味着int Typically short is a 16-bit integer, and int is a 32-bit integer. 通常, short是16位整数, int是32位整数。 That can cause weird effects. 那会导致怪异的效果。
  • You should start your loops at 2 instead of 3 . 您应该从2而不是3开始循环。 3 is already outside bounds. 3已经超出范围。
  • At the end of the final loop, all pointers will point beyond the ends of arrays, but you pass them to printf() anyway (which is actually undefined behavior). 在最后一个循环的末尾,所有指针都将指向数组的末尾,但是无论如何您都将它们传递给printf() (这实际上是未定义的行为)。
  • As a matter of fact, don't you want to output the contents of C[] - the addition results? 实际上,您是否不想输出C[]的内容-加法结果? Why are you using punt_A and punt_B there? 为什么在那里使用punt_Apunt_B

Now this is rough fix for ur program 现在这是您程序的粗略解决方案

#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;
}
  • In your program: 在您的程序中:

The problem was: You initialize an array of shorts. 问题是:您初始化短裤数组。 Size of short is 2 bytes. short的大小为2个字节。 However, you are loading number, expecting integer %d wich is 4 bytes. 但是,您正在加载数字,期望整数%d至4个字节。 So, you load in the 2 bytes, and the other two bytes just ommited. 因此,您加载了2个字节,而其他两个字节只是被忽略了。 I compile it WITHOUT -Wall -pedantic flags and still get warning: 我在没有-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]);

Now to fix this, make them all ints. 现在解决此问题,使它们全部为整数。 But you asked for better solution. 但是您要求更好的解决方案。 If you are given two arrays, and you have to sum them, and since you are using c++11, for you, it might be easier to use a container. 如果给了两个数组,并且必须将它们求和,并且由于您使用的是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;
}

Now notice, i made a define for your count. 现在注意,我为您的数量定义了一个定义。 Moreover, I used aray A again for output, saving space. 而且,我再次使用aray A进行输出,从而节省了空间。 The problem is, that vector by itself has O(n) complexity for push_back() (unless you resrve the size, but that requires knowing exact number of inputs, wich might not be in future a case, you might load until EOF). 问题在于,向量本身具有push_back()的O(n)复杂度(除非您减小大小,但是需要知道确切的输入数,否则将来可能不会出现,您可能要等到EOF才加载)。 To eliminate this and make the program faster, a list might be used for better performance. 为了消除这种情况并使程序更快,可以使用列表以获得更好的性能。

But if you WANT to use pointers, use iterators. 但是,如果您想使用指针,请使用迭代器。 :] :]

(please notice that my code is not protected for fails, meaning that if you put in a letter, it will do strange thing, but i outlined the idea :] (请注意,我的代码未得到保护,这意味着如果您写了一封信,它会做奇怪的事情,但我概述了这个想法:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM