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
Related
I've got a homework to create 2 functions add which adds element to dynamic array (what i've done) and remove which removes indicated element from that array. I have a problem with that 2nd function. I have no clue how to code it.
PS. I can't use memmove().
#include <stdlib.h>
#include <stdio.h>
void print_array(int *tab, int n);
void add(int x, int y, int *tab, int idx);
void remove_element(int *tab, int idx, int array_length);
int main() {
int *tab = malloc(24*sizeof(*tab));
int idx = 0;
tab[idx++] = 44;
tab[idx++] = 82;
tab[idx++] = 57;
tab[idx++] = 77;
printf("Before insert\n");
print_array(tab, idx);
idx++;
add(7, 0, tab, idx);
printf("After insert\n");
print_array(tab, idx);
free(tab);
idx--;
printf("After delete\n");
remove_element(tab, 3, idx);
print_array(tab, idx);
free(tab);
return(0);
}
void print_array(int *tab, int n) {
int i;
for (i = 0; i < n; i++) {
printf("t[%d] = %d\n", i, tab[i]);
}
}
void add(int x, int y, int *tab, int idx) {
int i;
for (i = idx; i > y; i--) {
tab[i] = tab[i-1];
}
tab[y] = x;
}
void remove_element(int *tab, int idx, int array_length) {
void *tmp = realloc(tab, (array_length - 1) * sizeof(int) );
array_length = array_length - 1;
tab = tmp;
}
About your array you can keep information about its size (eg iSize) and the number of elements in use (eg iUse). iUse<=isize, of course.
When you need to add an element but the array is too small (iUse==iSize), you increase its size, add the element and increment iUse.
When you remove an element, you just decrement iUse and, if you can't use memmov, make a loop to move al higher elements down.
I am trying to sort an array from least to greatest using pointers instead of array subscripts. I am not sure where the problem is but when i run this code, the values are returned in the same order that they were entered. The find_largest and swap functions both do exactly what they say. The selection_sort function uses a for loop to sort the numbers from right to left (greatest to smallest, right to left). I have been staring at this for a while now and it looks like it should work fine but like i said, for some reason the numbers are returned in the same order they were entered.
Here is my code:
#include <stdio.h>
#define N 5
void selection_sort(int *a, int n);
int *find_largest(int *a, int n);
void swap(int *p, int *q);
int main(void)
{
int i;
int a[N];
printf("Enter %d numbers to be sorted: ", N);
for (i = 0; i < N; i++)
scanf("%d", (a+i));
selection_sort(a, N);
printf("In sorted order:");
for (i = 0; i < N; i++)
printf(" %d", *(a+i));
printf("\n");
return 0;
}
void selection_sort(int *a, int n)
{
int i = 0;
int *largest;
for(i = 0; i < n; i++){
largest = find_largest(a, n-i);
swap(largest, a+(n-1-i));
}
}
int *find_largest(int *a, int n){
int *p = a;
int *largest = p;
for(p = a; p < a+n-1; p++){
if(*(p+1) > *p){
largest = (p + 1);
}
}
return largest;
}
void swap(int *p, int *q){
int *temp;
temp = p;
p = q;
q = temp;
}
There are two mistakes in your code.
One, logical in the find_largest function:
int *find_largest(int *a, int n){
int *p = a;
int *largest = p;
for(p = a; p < a+n-1; p++){
if(*(p+1) > *largest){ <---- //here you were checking for *(p)
largest = (p + 1);
}
}
return largest;
}
the other is with pointers in swap function:
void swap(int *p, int *q){
int temp;
temp = *p;
*p = *q;
*q = temp;
}
As John Bollinger mentioned in the comments, swap() does not function correctly - all it does is reassign pointers that quickly go out of scope.
Here is a rewrite of that function that does work. Just swap it in and it fits perfectly.
void swap(int *p, int *q){
int temp;
temp = *p;
*p = *q;
*q = temp;
}
Thanks to John Bollinger.
This program is supposed to take an array, and sort it from lowest to highest value. My program won't sort any values though. I believe the error is in the selectionSort. The values i and j are present in the function, I printed them out inside the function but they are not passed into the swap function. I tried making i and j pointers but it didn't work. I just have no clue on what to do next. Any help would be appreciated.
#include <stdio.h>
#define N 5
void selectionSort(int *a, int n);
int *findLargest(int *a, int n);
void swap(int *p, int *q);
int main(void)
{
int i;
int a[N];
printf("Enter %d numbers: ", N);
for (i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
selectionSort(a, N);
printf("In sorted order:");
for (i = 0; i < N; i++) {
printf(" %d", a[i]);
}
printf("\n");
return 0;
}
void selectionSort(int *a, int n)
{
int *p = a;
int i;
int j;
if (n == 1) {
return;
}
i = *(p+n-1);
j = *findLargest(a, n);
swap(&i, &j);
selectionSort(a, n - 1);
}
int *findLargest(int *a, int n)
{
int *p;
int *p_max = a;
for(p = a + 1; p < a + n - 1; p++) {
if ( *p > *p_max)
p_max = p;
}
return p_max;
}
void swap(int *p, int *q)
{
int temp = *(p-1);
*(p-1) = *q;
*q = temp;
}
The problem is in your call of swap: you swap the content of two local variables
int i;
int j;
... // Some other code, then
swap(&i, &j);
This has no effect on the original array. You should be passing p+n-1 and findLargest(a, n) directly, or store their results in pointers, not in ints:
swap(p+n-1, findLargest(a, n));
In addition, your swap is broken: rather than swapping the content of two pointers, it assumes that p points one element past the target location. This is a bad assumption to make in a general-purpose function, such as swap, and it also leads to undefined behavior in your program.
void swap(int *p, int *q) {
int temp = *p;
*p = *q;
*q = temp;
}
I'm trying to write a program that dynamically allocates memory for an array, which the user then fills with integer values and the program sorts said integer values. However, it seems that my array isn't working as intended. I have managed to get the program working with a static array, but the dynamic allocation is causing me a lot of problems with incorrect values and whatnot. Here's what I have so far for the dynamically allocated version (if it would help you guys, I can also provide the version that uses a static array):
#include <stdio.h>
#include "genlib.h"
#include "simpio.h"
void sortArray (int *numbers, int i2);
int indexMax (int *numbers, int low, int high);
void swap (int *num1, int *num2);
int getArray (int *numbers);
void displayArray (int *numbers, int i2);
main()
{
int *numbers, i2;
i2=getArray(numbers);
sortArray(numbers, i2);
displayArray (numbers, i2);
}
int getArray (int *numbers)
{
int i, i2;
printf("Please enter the amount of elements you wish to sort: ");
i2=GetInteger();
numbers=(int *)malloc(i2*sizeof(int));
for(i=0;i<i2;i++, numbers++)
{
printf("Enter next integer: ");
*numbers=GetInteger();
printf("\n");
}
return(i2);
}
void displayArray (int *numbers, int i2)
{
int i;
printf ("\nThe sorted list is: \n\n");
for (i=0;i<i2;i++, numbers++)printf ("%d\n", *numbers);
}
void sortArray (int *numbers, int i2)
{
int i, minInd;
for(i=0;i<i2;i++)
{
minInd=indexMax(numbers, i, i2-1);
swap(&numbers[i], &numbers[minInd]);
}
}
int indexMax (int *numbers, int low, int high)
{
int i, maxInd;
maxInd=high;
for (i=high;i>=low;i--)
{
if(*(numbers+i)>*(numbers+maxInd)) maxInd=i;
}
return (maxInd);
}
void swap (int *num1, int *num2)
{
int temp;
temp=*num1;
*num1=*num2;
*num2=temp;
}
Here is a working solution:
#include <stdio.h>
#include <stdlib.h>
void sortArray (int *numbers, int i2);
int indexMax (int *numbers, int low, int high);
void swap (int *num1, int *num2);
int getArray (int **numbers);
void displayArray (int *numbers, int i2);
main()
{
int *numbers, i2;
i2=getArray(&numbers);
sortArray(numbers, i2);
displayArray (numbers, i2);
}
int getArray (int **numbers)
{
int i, i2;
printf("Please enter the amount of elements you wish to sort: ");
scanf("%d", &i2);
(*numbers) = malloc(i2 * sizeof(int));
int *temp = *numbers;
for(i = 0; i < i2; i++)
{
printf("Enter next integer: ");
scanf("%d", &temp[i]);
printf("\n");
}
return(i2);
}
void displayArray (int *numbers, int i2)
{
int i;
printf ("\nThe sorted list is: \n\n");
for (i=0;i<i2;i++, numbers++)printf ("%d\n", *numbers);
}
void sortArray (int *numbers, int i2)
{
int i, minInd;
for(i=0;i<i2;i++)
{
minInd=indexMax(numbers, i, i2-1);
swap(&numbers[i], &numbers[minInd]);
}
}
int indexMax (int *numbers, int low, int high)
{
int i, maxInd;
maxInd=high;
for (i=high;i>=low;i--)
{
if(*(numbers+i)>*(numbers+maxInd)) maxInd=i;
}
return (maxInd);
}
void swap (int *num1, int *num2)
{
int temp;
temp=*num1;
*num1=*num2;
*num2=temp;
}
The thing is in your main when you are declaring int *numbers , numbers pointer is pointing to some junk memory location as local variables can have any garbage value, so while you are passing this numbers pointer to getArray() function you are passing its value, Suppose numbers is pointing to some random value = 1234 and suppose address of numbers is = 9999. Now when you call getArray(numbers) you tell taht whatever is there in numbers pass it to getArray's numbers variable that we are letting is 1234.
Then when you allocate memory to numbers that is local variable of getArray() function not main's and it might have address suppose = 0x8888. Then malloc allocates some address space as specified and stores the start address of that allocated address space(suppose i.e. = 0x7777) into location 0x8888 not 0x9999 which is the adress of main's numbers variable.
Thus when the getArray function ends and next time you call sortArray you pass it value present in numbers variable of main which is still junk 1234. and the actual value you should be passing is present at address 0x8888.
Try this:
int main(void)
{
int *numbers, i2;
i2 = getArray(&numbers);
sortArray(numbers, i2);
displayArray (numbers, i2);
return 0;
}
int getArray (int **numbers)
{
int i, i2;
printf("Please enter the amount of elements you wish to sort: ");
i2 = GetInteger();
*numbers = malloc(i2 * sizeof int);
etc...
You simply need one more level of indirection to make int getArray(int**) return a pointer to an allocated array.
As an aside, you can use the C library function qsort() to do the sorting work for you. Here is an example:
int main(void)
{
int a[]={4,7,9,1,34,90,66,12};
qsort(a, sizeof(a)/sizeof(a[0]), sizeof(int), compare);
return 0;
}
int compare(const void *a, const void *b){
const int *x = a, *y = b;
if(*x > *y)
return 1;
else
return(*x < *y) ? -1: 0;
}
Works just as well with dynamically allocated int arrays, or char arrays
Actually this is a pure C prog.when i compile with Xcode. error
message says "pointer being realloc'd was not allocated"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int LocateElem(int *p1,int e,int leng1);
void Display(int max, int array[]);
int GetElem(int * p, int pass);
int Union(int *p1,int *p2, int leng1, int leng2);
int ListInsert(int *p, int e, int lengA);
int* GetData(int* pArray, int Array_size);
void Show(int *p, int leng);
void InitList_Sq(int *L);
int *p_A,*p_B;
int m,n;
int main()
{
clock_t begin, end;
double cost;
begin = clock();
printf("How many elements of A u want:");
scanf("%d",&m);
if (m<0) {
printf("Error!");
return 0;
}
printf("How many elements of B u want:");
scanf("%d",&n);
if (n<0) {
printf("Error!");
return 0;
}
p_A=(int *)malloc(m*sizeof(int));
p_B=(int *)malloc(n*sizeof(int));
if (p_A==NULL) {
printf("Error allocating memory!\n"); //print an error message
return 0; //return with failure
}
if (p_B==NULL) {
printf("Error allocating memory!\n"); //print an error message
return 0; //return with failure
}
int *pLast_A, * pLast_B;
printf("Array A is :\n");
pLast_A=GetData(p_A, m);
printf("\nArray B is :\n");
pLast_B=GetData(p_B, n);
int newLeng;
newLeng=Union(p_A,p_B,m,n);
printf("\nThe Union set is :\n");
Show(p_A, newLeng);
free(p_A);
free(p_B);
end = clock();
cost = (double)(end - begin) / CLOCKS_PER_SEC;
printf("\n%lf seconds", cost);
return 1;
}
int* GetData(int* pArray, int Array_size){
int* pFill= pArray;
int count;
srand((unsigned) time(NULL));
for ( count=0; count< Array_size; count++) {
*(pFill+count)=rand()%1000;
printf("%d\t", * (pFill+count));
}
return pFill+count;
}
int Union(int *p1,int *p2, int leng1, int leng2){
for (int count=0; count<leng2; count++) {
int e=GetElem(p2, count);
while(LocateElem(p1, e, leng1)==0){
leng1=ListInsert(p1, e, leng1);
}
}
return leng1;
}
int GetElem(int *p, int pass){
return *(p+pass);
}
int LocateElem(int *p1,int e,int leng1){
for (int count=0; count<leng1; count++)
if (e==*(p1+count))
return 1;
else
return 0;
}
int ListInsert(int *p, int e, int lengA){
lengA+=1;
int* temp;
temp=(int*)realloc(p, lengA*sizeof(int));
if (temp==NULL) {
printf("Error allocating memory!\n"); //print an error message
free(temp);
return 0; //return with failure
}
else{
p=temp;
*(p+lengA-1)=e;
}
return lengA;
}
void Show(int *p, int leng){
for (int count=0; count<leng; count++) {
printf("%d\t", *(p+leng));
}
}
After compilation xcode gives the breakpoint at the line temp=(int*)realloc(p, lengA*sizeof(int)) with signal SIGABRT.
The problem is that here:
int ListInsert(int *p, int e, int lengA){
int* temp;
temp=(int*)realloc(p, lengA*sizeof(int));
...
else {
p=temp; // <<<<< THIS
the new value of p does not propagate back to the ListInsert's caller. This happens because p is passed by value.
You need to turn int *p into int **p.