简体   繁体   中英

[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.

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

  • Pointer U inside suma_vectori is uninitialized, causing undefined behavior on assignment
  • Assignment *S= suma_vectori(n,X,Y) has no effect beyond the initial element of 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:

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

as it is picking garbage value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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