I'm new to pointers and this may be a silly question.
Not able to store float numbers into float array using void pointer. Below is the code and the output:
Code:
int main()
{
int size=5;
float f_array[size];
populate(f_array, size);
// printing array below
}
void populate(void *p, int size)
{
int i;
for(i=0; i<size; i++)
{
scanf("%f", (((float *)p)+i));
}
}
Output:
//Entering five float numbers to be stored in array
1.2 // not able to enter other numbers and gives the below output
a[0] = 1
a[1] = garbage value
a[2] = garbage value
a[3] = garbage value
a[4] = 0
#include <stdio.h>
#define SIZE 5
void populate(void *p, int size)
{
int i;
float *array = (float*)p;
for (i = 0; i < size; i++)
{
scanf("%f", &array[i]);
}
}
int main()
{
int i;
float f_array[SIZE];
populate(f_array, SIZE);
//print array
}
Related
#include <stdio.h>
#include <math.h>
void abs_table (double x[], int size);
int main (void) {
int size, index;
printf("Enter number of elements: ");
scanf("%d", &size);
double x[size], element;
for (index = 0; index < size; index++) {
printf("Enter x[%d]: ", index);
scanf("%lf", &element);
x[index] = element;
}
void abs_table (double x[], int size);
return 0;
}
void abs_table (double x[], int size) {
int index;
double y[size];
for (index = 0; index < size; index++) {
y[index] = fabs(x[index]);
printf("%lf\t%lf\n", x, y);
}
}
program to read in array values and display the absolute value of each element using a void function.
program terminates after storing values into array x. void function does not display.
Call abs_table() instead of declaring it in main().
Index x and y in abs_table() print statement. As you don't use y other than to print the current value eliminate it.
(minor) Move main() after function so you don't need the declaration.
(minor) Minimize scope of variables.
(minor, not fixed) If your size argument is before x, then you can document their relationship void abs_table(int size, double x[size]).
(minor. not fixed) prefer unsigned variables (index, size etc).
(not fixed) check if scanf() returns 1 in your code otherwise the values size and x[index] may be undefined.
#include <stdio.h>
#include <math.h>
void abs_table (double x[], int size) {
for (int index = 0; index < size; index++) {
printf("%lf\t%lf\n", x[index], fabs(x[index]));
}
}
int main (void) {
int size;
printf("Enter number of elements: ");
scanf("%d", &size);
double x[size];
for (int index = 0; index < size; index++) {
printf("Enter x[%d]: ", index);
scanf("%lf", &x[index]);
}
abs_table(x, size);
return 0;
}
Here is an example run;
Enter number of elements: 3
Enter x[0]: -1.2
Enter x[1]: 1.3
Enter x[2]: -100
-1.200000 1.200000
1.300000 1.300000
-100.000000 100.000000
For n=3 and a={1,2,3},b={4,5,6} its supposed to calculate 1*4+2*5+3*6.
I don't understand why does it work because p is a pointer and p=produs(a,b,n) means that the address of p becomes the value returned by produs.
#include <stdio.h>
#include <conio.h>
void citire(int *x,int *n)
{
for(int i=1; i<=*n; i++)
scanf("%d",&x[i]);
}
int produs(int *a,int*b,int n)
{
int produs=0;
for(int i=1;i<=n;i++)
produs=a[i]*b[i]+produs;
return produs;
}
int main()
{
int n;
int*p;
scanf("%d",&n);
int *a=(int*)malloc(n*sizeof(int));
int *b=(int*)malloc(n*sizeof(int));
citire(a,&n);
citire(b,&n);
p=produs(a,b,n);
printf("%d",p);
return 0;
}
When you do:
size_t size = 10;
int* x = calloc(size, sizeof(int));
You get an array x with 10 items in it, indexed 0..9, not 1..10. Here calloc is used to make it abundantly clear what's being requested instead of doing multiplication that can be mysterious or obtuse.
As such, to iterate:
for (int i = 0; i < size; ++i) {
x[i] ...
}
You have a number of off-by-one errors in your code due to assuming arrays are 1..N and not 0..(N-1).
Putting it all together and cleaning up your code yields:
#include <stdio.h>
#include <stdlib.h>
void citire(int *x, size_t s)
{
for(int i=0; i < s; i++)
scanf("%d", &x[i]);
}
int produs(int *a, int* b, size_t s)
{
int produs = 0;
for(int i = 0; i < s; i++)
produs = a[i] * b[i] + produs;
return produs;
}
int main()
{
int n;
scanf("%d",&n);
int* a = calloc(n, sizeof(int));
int* b = calloc(n, sizeof(int));
citire(a, n);
citire(b, n);
// produs() returns int, not int*
int p = produs(a,b,n);
printf("%d", p);
return 0;
}
You're using pointers in places where pointers don't belong. In C passing a pointer to a single value means "this is mutable", but you don't change those values, so no pointer is necessary nor advised.
Try and use size_t as the "size of thing" type. That's what's used throughout C and it's an unsigned value as negative indexes or array lengths don't make any sense.
as you can tell by the title I need to write a function that returns a pointer to the largest number in an array, the functions gets a pointer to a double array and it's size. In addition I need to write a main function that will use this function.
Here is the code that I wrote:
#include <stdio.h>
#include <stdlib.h>
void BigEl(double* arr, double arrSize);
void BigEl(double* arr, double arrSize)
{
int i;
double maximum, *x;
maximum = arr[0];
for (i = 1; i < arrSize; i++)
{
if (arr[i]>maximum)
{
maximum = arr[i];
}
}
*x = maximum;
}
void main()
{
double myarr[10];
int i;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i < 10; i++)
{
scanf("%d", &myarr[i]);
}
BigEl(myarr, 10);
}
I get this error:
Error 1 error C4700: uninitialized local variable 'x' used
I don't understand what I did wrong because I did initialized x.
Any kind of help is appreciated, in addition, tell me if the idea of my code was right because Im not sure if I understood the question correctly.
You did not initialize the variable x. You merely wrote to the the location pointed to by x, here:
*x = maximum;
when x was uninitialized, which is what the compiler is complaining about.
You want something like:
double *
BigEl(double* arr, size_t arrSize)
{
size_t i;
double *max = arr;
for (i = 1; i < arrSize; i++)
if (arr[i] > *max)
max = &arr[i];
return max;
}
Things I've changed:
Use size_t for the array size and the counter, not a double and an int.
Retain a pointer to the maximum element, not the maximum element's value.
Return the pointer to the maximum element.
Remove superflous braces.
You're not returning anything. Also, it might be good to take into consideration the case when the array size is 0. Moreover, the size should be passed as a constant. No other answer has mentioned this.
double* BigEl(double* arr, const size_t iSize)
{
if(iSize == 0)
return 0;
double max = arr[0], *x = &arr[0];
for(unsigned int i=1;i<iSize;++i){
if(arr[i] > max){
max = arr[i];
x = &arr[i];
}
}
return x;
}
Your assignment to *x is incorrect - you are saying "assign to the location pointed to by x, without first saying where that is. Aside from that, there are a couple of other issues:
#include <stdio.h>
#include <stdlib.h>
// return pointer to location from function
double * BigEl(double* arr, double arrSize)
{
int i;
// initialise both variables
double maximum = arr[0], *max_pos = arr;
for (i = 1; i < arrSize; i++)
{
if (arr[i]>maximum)
{
maximum = arr[i];
// assign address here
max_pos = &arr[i];
}
}
// return address
return max_pos;
}
int main()
{
double myarr[10];
double * max_pos;
int i;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i < 10; i++)
{
scanf("%lf", &myarr[i]);
}
// use return value here
max_pos = BigEl(myarr, 10);
return 0;
}
//function that returns a pointer to the largest number
double *BigEl(double* arr, int arrSize)
{
int i;
double *maximum;
maximum = &arr[0];
for (i = 1; i < arrSize; i++)
{
if (arr[i] > *maximum)
{
maximum = &arr[i];
}
}
return maximum;
}
int main(void)
{
double myarr[10];
int i;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i < 10; i++)
{
scanf("%lf", &myarr[i]);
}
printf("%f\n", *BigEl(myarr, 10));
return 0;
}
I need to write a function that returns a pointer to the largest
number in an array
I think you need the follwoing
#include <stdio.h>
double * largest_element( const double *a, int n )
{
const double *largest = a;
int i;
for ( i = 1; i < n; i++ )
{
if ( *largest < a[i] ) largest = a + i;
}
return ( double *)largest;
}
#define N 10
int main(void)
{
double a[N];
int i;
printf("Please insert %d numbers to the array: ", N );
for ( i = 0; i < N; i++ )
{
scanf( "%lf", &a[i] );
}
printf( "\nThe largest element of the array is %lf\n", *largest_element( a, N ) );
return 0;
}
If to enter for example
2.2 1.5 5.2 1.8 3.9 5.9 7.7 6.8 2.9 0.8
then the program output will be
The largest element of the array is 7.700000
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
I've been trying to write a void function called printReverse that takes a double array named d and an int called n as arguments, where n is the number of elements in d. I want printReverse to print the n array values in reverse order. This is what I have so far, but I'm having difficulty declaring arguments.
#include <stdio.h>
int n
double d[n]
void printReverse(d[], double newArray){
int i;
int j;
for (i=0; j=n-1; i<n; i++; j--;){
newArray[j]=d[i];
}
printf("%lf\n",newArray);
}
Any help in what I'm doing wrong would be very much appreciated.
REVISION: Would this code work
void printReverse(double [] d, int n){
int i;
for(i=n-1;i>=0;i--){
printf("%f\n",d[i]);
}
If you want both print and store the array in reverse order you could do something like this:
#include <stdio.h>
void printReverse(double *d, double *newArray, int n){
int i;
int j;
for (i=0, j=n-1; i<n; i++, j--){
newArray[i]=d[j];
printf("%lf\n",newArray[i]);
}
}
int main(){
int n = 4;
double array[] = {1, 2, 3, 4};
double newArr[n];
printReverse(array,newArr,n);
}
//take pointer to array, and size of array as parameters
void printReverse(double* arr,int size){
for(int i =0;i<size;i++){
printf("%f\n",arr[(size-1)-i]);
//(size-1)-i will compute the proper index of the array to read backwards.
//remeber arrays are 0 based meaning that the first member in the array is index 0
}
}
this should do the trick.
EDIT: or if you are trying to reverse the array into a new array and then print...
void printReverse(double* arr,double* arr2,int size){
for(int i =0;i<size;i++){
arr2[(size-1)-i]=arr[i];
}
for (int i=0; i<size; i++) {
printf("%f\n",arr2[i]);
}
}
you will need to have the arrays in the code that calls this function.
so...
double arr[5] = {1,2,3,4,5};
double arr2[5];
printReverse(arr,arr2, 5);