【问题标题】:Small program that uses pointers to sum integers使用指针对整数求和的小程序
【发布时间】:2020-03-27 09:08:16
【问题描述】:

我需要创建一个程序来计算动态分配的向量的累积和,并且向量应该用随机值填充(不是来自标准输入的值)使用only pointers。我想不出只使用指针的版本(我对这个问题有点陌生)。

这是我目前的代码:

#include <stdio.h>
#include <malloc.h>

int main()
{
    int i, n, sum = 0;
    int *a;

    printf("Define size of your array A \n");
    scanf("%d", &n);

    a = (int *)malloc(n * sizeof(int));
    printf("Add the elements: \n");

    for (i = 0; i < n; i++)
    {
        scanf("%d", a + i);
    }
    for (i = 0; i < n; i++)
    {
        sum = sum + *(a + i);
    }

    printf("Sum of all the elements in the array = %d\n", sum);
    return 0;
}

【问题讨论】:

  • 如果你所说的“脚本”只是一个函数定义,那么你根本不需要使用静态变量。接受一个作为向量开始的指针;然后,您将需要一些约定来结束向量,例如值为零,或者还接受另一个参数,即向量的长度或指向向量末尾的指针,然后遍历向量将值相加。我猜这个想法是你不使用 int 作为你的循环变量,而是在你去的时候增加指针。
  • 我不认为没有指针就可以做到这一点,因为您需要 int 变量来存储数组长度和循环索引。除了一些没有人会在现实生活中使用的骇人听闻的技巧。
  • 不要使用*(a + i),而是使用更惯用的a[i]。同样在scanf 中,不要使用a + i,而是使用&amp;a[i]。是一样的,但是没有人写*(a + i)。
  • 您确定您没有误解“仅使用指针”的要求吗?这个要求对我来说听起来很愚蠢。
  • @Jabberwocky 我没有,相信我.. 听起来很愚蠢

标签: c pointers sum malloc dynamic-arrays


【解决方案1】:

这并没有那么复杂,而不是声明int 变量,您需要声明int 指针,然后为它们分配内存。

类似:

Running sample

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int *n = malloc(sizeof(int)); //memory allocation for needed variables
    int *sum = malloc(sizeof(int));
    int *a;

    srand(time(NULL)); //seed

    printf("Define size of your array A \n");
    scanf("%d", n);

    if (*n < 1) {                  //size must be > 0
        puts("Invalid size");
        return 1;
    }

    printf("Generating random values... \n");
    a = malloc(sizeof(int) * *n); //allocating array of ints
    *sum = 0;                     //reseting sum

    while ((*n)--) {
        a[*n] = rand() % 1000 + 1; // adding random numbers to the array from 1 to 1000
        //scanf("%d", &a[*n]); //storing values in the array from stdin
        *sum += a[*n];       // adding values in sum
    }

    printf("Sum of all the elements in the array = %d\n", *sum);
    return 0;
}

编辑

添加随机数生成而不是标准输入值

【讨论】:

  • 需要用随机值填充向量,而不是从标准输入中获取它们
  • @JonBjatBun,我更改了答案以适应您的规范。
【解决方案2】:

你可以用这样的东西代替静态变量

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

【讨论】:

  • 满足愚蠢要求的好主意(仅使用指针)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多