简体   繁体   English

[C编程]向量和指针

[英][C Programming]Vectors & Pointers

I don't have idea where is the problem but the latest pointer(vector) have some troubles.我不知道问题出在哪里,但最新的指针(向量)有一些麻烦。 First value it's ok (V[0]+T[0]) , S[1] it's always 0 and third value it's random.第一个值没问题(V[0]+T[0])S[1]始终为 0,第三个值是随机的。

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

int citire_vector(int n, int *V);
void afisare_vector(int n, int *V);
int produs_scalar(int n, int *V, int *T);
int suma_vectori(int n, int *V, int *T);

int main(void)
{
    int n, *X, *Y, ps, *S;
    printf("n = ");
    scanf("%d",&n);

    X = (int*) malloc(n*sizeof(int));
    Y = (int*) malloc(n*sizeof(int));

    citire_vector(n,X);
    citire_vector(n,Y);
    afisare_vector(n,X);
    afisare_vector(n,Y);

    ps = produs_scalar(n,X,Y);
    printf("Produsul scalar = %d\n",ps);

    S = (int*) malloc(n*sizeof(int));
    *S= suma_vectori(n,X,Y);
    afisare_vector(n,S);

}

int citire_vector(int n, int *V)
{
    int i;

    for(i=0;i<n;i++)
        scanf("%d",V+i);

    return *V;
}

void afisare_vector(int n, int *V)
{
    int i;
    printf("Valorile vectorului sunt:\n");
    for(i=0;i<n;i++)
        printf("%d ",*(V+i));
    printf("\n");
}

int produs_scalar(int n, int *V, int *T)
{
    int i, ps = 0;
    for(i = 0;i<n;i++)
        ps += (*(V+i))*(*(T+i));
    return ps;
}

int suma_vectori(int n, int *V, int *T)
{
    int i, *U;
    for(i=0;i<n;i++)
    {
        *(U+i )= *(V+i);
    }
    return *U;
}

Your suma_vectori and its usage are incorrect.您的suma_vectori及其用法不正确。

  • Pointer U inside suma_vectori is uninitialized, causing undefined behavior on assignment suma_vectori指针U未初始化,导致赋值时出现未定义的行为
  • Assignment *S= suma_vectori(n,X,Y) has no effect beyond the initial element of S赋值*S= suma_vectori(n,X,Y)S的初始元素没有影响

To fix this problem, change suma_vectori to return int* , move malloc of the result inside the function, remove malloc for S , and assign S the result of the suma_vectori call:要解决此问题, suma_vectori更改为 return int* ,将结果的malloc移动到函数内,删除S malloc ,并将suma_vectori调用的结果分配给S

int *suma_vectori(int n, int *V, int *T); // forward declaration

int *suma_vectori(int n, int *V, int *T) { // Implementation
    int *U = malloc(n*sizeof(int)); // do not cast malloc
    for(int i=0;i<n;i++) {
        U[i] = V[i] + T[i];
    }
    return U;
}

// call
S= suma_vectori(n,X,Y);

// Don't forget to free malloc-ed memory
free(X);
free(Y);
free(S);

You have to allocate memory to U in suma_vectori function您必须在 suma_vectori 函数中为 U 分配内存

as it is picking garbage value因为它正在挑选垃圾价值

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

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