I have to write a C program to do the following:
Write a function that takes three arguments: a pointer to the first
element of a range in an array, a pointer to the element following
the end of a range in an array, and an int value. Have the function
set each element of the array to the int value.
My code is not working. Here is what I have so far. Any help is appreciated.
#include <stdio.h>
#include <iostream>
int listNumbers[3]{ 1,2,3 };
void Sorter(int *first, int * last, int *value);
int * first = &listNumbers[0];
int * last = &listNumbers[2];
int value;
int main() {
printf("your list numbers are:\n");
int i;
for (int i = 0; i < 3; ++i) {
printf("%d", listNumbers[i]);
}
printf("\n");
printf("enter an integer:\n");
scanf_s("%d", &value);
Sorter( first, last, &value);
printf("your new list numbers are:\n");
int j;
for (int j = 0; j < 3; ++j) {
printf("%d", listNumbers[j]);
}
printf("\n");
system("PAUSE");
return 0;
}
void Sorter(int *first, int * last, int *value) {
int i=0;
printf("value = %d\n", &value);
*first = value;
while (i <= *last) {
*(first + i) = value;
i++;
}
}
First, work out the different between the 2 pointers.
int count = last - first + 1;
The compiler will automatically divide by the size of an integer. We add 1 to make the range inclusive. Now just iterate through each element:
for (int i = 0; i < count; i++) {
first[i] = value;
}
Also, why are you passing the value as a pointer? This should just be a value.
void Sorter(int *first, int *last, int value) {
And when you call it...
Sorter(first, last, value);
Your Sorter function does not satisfy the problem criteria. The parameters are supposed to be two pointers into an array, and an int. Your function instead accepts three pointers.
You could nevertheless have made it implement at least the apparent spirit of the exercise, by using the value to which the third argument points as the fill value, but you don't do that. Instead you assign the pointer itself to each array element. That ought to at least elicit a warning from your compiler, and you ought not to be ignoring its warnings, especially when your code it not doing what you think it should.
Furthermore, the last pointer is expected to point to just past the last element to set, but you use it as if it points to an integer offset from the start pointer. This is almost the opposite of the previous problem: here, you need to use the pointer value itself, not the int to which it points.
Related
Basically I have a function called MinSubTab that is supposed to calculate the sum of the array passed and also to change the value passed in the first argument from inside the function without using return. This is done with pointers. Anyway, I think it'd be easier if I just showed you the code so here it is:
maintab.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "tab.h"
int main(){
int *reftab;
int min;
reftab = (int *)malloc(sizeof(int) * NMAX);
InitTab(reftab,NMAX);
printf("\n Total: %d et min: %d", MinSumTab(&min, reftab, NMAX), min);
free(reftab);
return 0;
}
tab.c
void InitTab(int *tab, int size){
srand(time(NULL));
for (int i=0; i<size; i++){
*(tab+i) = rand() % 10;
}
}
int MinSumTab(int *min, int *tab, int size){
int total=0;
int minimum = NMAX;
int temp = *min;
for (int i=0; i<size; i++){
total += *(tab+i);
}
for (int i=0; i<size; i++){
if(*(tab+i)<minimum){
minimum = *(tab+i);
}
}
*min = minimum;
return total;
}
So the expected result here is that the sum is printed (which it is) and the minimum value of the array is printed (which it is not). Every single time the min variable equals 8 and I've no idea how to actually change the value of min from within that function.
Please help as my brain has no more capacity for rational thought, it's been 1.5 hrs and no solution in sight. Thanks
Looks like a small mistake:
You initialize minimum with NMAX, which I assume is 8 (the size of the array). 99.9% of the random numbers will be bigger. So 8 is chosen as the minimum.
What you really want is to initialize it with RAND_MAX – the maximum value rand() can return.
In C order of evaluation and argument passing is undefined.
You can of course the order yourself but it only to feed your curiosity.
#include <stdio.h>
volatile char *message[] = {
"fisrt", "second", "third", "fourth"
};
int print(size_t x)
{
printf("%s\n", message[x]);
return x;
}
int main()
{
printf("%d %d %d %d\n", print(0), print(1), print(2), print(3));
return 0;
}
Note. There is one exception from this rule.
Logical operators are evaluated form the left to the right.
if( x != NULL && *x == 5)is safe because x will not be dereferenced if it is NULL
I'm trying to create a function that returns as its result the sum of the elements in the array. When I try to run the program, I get a segmentation fault. Could someone please point me in the right direction? Thank you!
int arraySum (int array[], int numberOfElements) {
int result = 0;
for (int i = 0; i < numberOfElements; i++)
{
result += array[i];
}
return result;
}
int main (void) {
int numberOfElements;
int *array = NULL;
printf("How many elements would you like in your array: ");
scanf("%i", &numberOfElements);
printf("\nPlease list the values of the elements in the array: ");
for (int i = 0; i < numberOfElements; i++)
{
scanf("%i", &array[i]);
}
int result = arraySum(array, numberOfElements);
return result;
}
The problem you have is, that in C you need to manually allocate the memory if you are using a pointer instead of say a fixed-size array.
This is usually done by calling malloc, which will return a void-pointer (void*), which you need to cast to the desired type (in your case (int*)) before assigning it.
It is also important to note, that, when using malloc, you need to specify the amount of Bytes you want to allocate. This means that you can't just call it with the number of integers you want to store inside, but rather have to multiply that number with the amount of Bytes that one integer occupies (which depends on the Hardware and Operating System you use, hence you should use sizeof(int) for that purpose, which evaluates to that size at compile time).
I modified your code with a working example of how it could be done:
#include <stdio.h>
#include <stdlib.h>
int arraySum (int array[], int numberOfElements) {
int result = 0;
int i;
for (i = 0; i < numberOfElements; i++) {
result += array[i];
}
return result;
}
int main(int argc, char **argv) {
int numberOfElements;
int *array = NULL;
printf("How many elements would you like in your array: ");
scanf("%i", &numberOfElements);
array = (int*) malloc(numberOfElements * sizeof(int));
printf("\nPlease list the values of the elements in the array: ");
int i;
for (i = 0; i < numberOfElements; i++) {
scanf("%i", &array[i]);
}
int result = arraySum(array, numberOfElements);
printf("\n\nThe result is: %d\n", result);
return 0;
}
You are also trying to return the result in your main function, but the return value of main in C is used to signal whether your program terminated without errors (signalled by a return value of 0) or didn't encounter any issues (any value other than 0).
You need to allocate memory. It is not enough to just declare a pointer. You do it like this: array=malloc(numberOfElements*sizeof(*array));
Also, although it is possible to return result from the main function, you should not do that. The return value from main is usually used for error checking. Change the end of your program to
printf("Sum: %d\n", result);
return 0;
Returning 0 usually means that no error occurred.
I want to pass two arguments into void Dividing from void Assign_numbers and void Maximum. I have only learnt to pass one argument at a time. Can you please tell me what I have to do print out the following variables inside void Dividing. If it's possible, I don't want the format of my code to change drastically. Can you also show me an example, since I am a visual learner. Thanks
#include <stdlib.h>
#include <stdio.h>
#define Max 6
struct Numbers
{
double a,b,c,d,e,f;
};
void Maximum(double *ptr);
void Dividing(double Maximum, double *ptr);
void Assign_numbers()
{
struct Numbers number;
number.a=45.78;
number.b=81.45;
number.c=56.69;
number.d=34.58;
number.e=23.57;
number.f=78.35;
Maximum((double*) &number);
Dividing((double*) &number);
}
void Maximum(double *ptr)
{
int i=0;
double Maximum = ptr[0];
for(i;i<Max;i++)
{
if(ptr[i]> Maximum)
{
Maximum = ptr[i];
}
}
Dividing(Maximum);
}
void Dividing(double Maximum, double *ptr)
{
printf("%.2f", Maximum);
printf("%.2f",ptr[3]);
}
int main()
{
Assign_numbers();
return 0;
}
Use array instead of struct - shwon here with reference example
Like Joachim Pileborg said. Don't use a struct as an array. In your case use a multidimensional array.
double[10][6] numbers;
You can easily iterate through such an array like so:
#include <stdio.h>
int main () {
/* an array with 2 rows and 6 columns*/
double numbers[2][6] = {
{45.78, 81.45, 56.69, 34.58, 23.57, 78.35},
{1,2,3,4,5, 6}
};
int i, j;
/* output each array element's value */
for ( i = 0; i < 2; i++ ) {
for ( j = 0; j < 6; j++ ) {
printf("numbers[%d][%d] = %f\n", i,j, numbers[i][j] );
}
}
/* Output by reference */
for(i = 0; i < 2; i++){
for(j=0; j < 6; j++ ){
printf("numbers[%d][%d] = %f\n", i, j,*(*(numbers + i) + j));
}
}
return 0;
}
Why the current code fails
Now onto explaining how your code (does not) work and a little about how pointers work. First off:
Dividing(double Maximum, double* ptr);
Does not work in the way you think it does. "double Maximum" is a new double variable that works within the scope of Dividing and is not a variable retrieved from the function:
void Maximum(double *ptr);
If you already knew this, then you should know or at least have expected how poor the naming of your variables are(keep it lowerCamelCase).
Now lets get onto what you're trying to do. IMHO your code is completely broken unless I am noticeing something. In Assign_numbers() you want to call Dividing() using a pointer reference. In Maximum() you want to call Dividing() again, but this time sending only a value. It doesn't make it better that you have 2 separate different calls that each have one parameter. But the function has to have two parameters. Now in order to iterate through the variables in a struct - again this is not recommended and the bottom code only serves as an example.
struct Numbers
{
double a,b,c,d,e,f;
};
struct Numbers Assign_numbers()
{
struct Numbers number;
number.a=45.78;
number.b=81.45;
number.c=56.69;
number.d=34.58;
number.e=23.57;
number.f=78.35;
return number;
}
int main()
{
struct Numbers number;
number = Assign_numbers(number);
double *value = &(number.a); //take address of the first element, since a pointer always counts upwards.
int i;
/*This loops through the addresses of the struct starting from the initial address in number.a and moves upwards 5 times and hopefully ends in number.f. Seriously bad way to construct arrays*/
/*Just try replacing sizeof(number) with sizeof(double). suddenly you get all kinds of weird values because you have ended up outside of the struct*/
/*Also note that this only works when all the datatypes in the struct have a size of 8 bytes(the size of double) */
for (i = 0; i < sizeof(number) / sizeof(double); i++){
printf("[%d]: %f\n",i, value[i]);
}
return 0;
}
New working code
With all that said. This is the closest I am going to to be able to make your code work since I have no idea what you're trying to accomplish:
#include <stdlib.h>
#include <stdio.h>
#define Max 6
struct Numbers
{
double a,b,c,d,e,f;
};
void Maximum(double *ptr);
void Dividing(double *ptr);
void Assign_numbers()
{
struct Numbers number;
number.a=45.78;
number.b=81.45;
number.c=56.69;
number.d=34.58;
number.e=23.57;
number.f=78.35;
Maximum(&number.a); //You need to parse the very first address of the struct. IN this case 'a'
Dividing(&number.a);
}
void Maximum(double *ptr)
{
int i=0;
double maximum = ptr[0];
for(i;i<Max;i++)
{
if(ptr[i]> maximum)
{
maximum = ptr[i];
}
}
printf("maximum: %f", maximum);
}
/*//removed the first parameter since it was not clear what it was for and you only had function calls to this function with one parameter */
void Dividing(double *ptr)
{
printf("%.2f",ptr[3]);
}
int main()
{
Assign_numbers();
return 0;
}
I'm a java student who's currently learning about pointers and C.
I tried to make a simple palindrome tester in C using a single array and pointer arithmetic.
I got it to work without a loop (example for an array of size 10 :*(test) == *(test+9) was true.
Having trouble with my loop. School me!
#include<stdio.h>
//function declaration
//int palindrome(int *test);
int main()
{
int output;
int numArray[10] = {0,2,3,4,1,1,4,3,2,0};
int *ptr;
ptr = &numArray[0];
output = palindrome(ptr);
printf("%d", output);
}
//function determine if string is a palindrome
int palindrome(int *test) {
int i;
for (i = 0; i <= (sizeof(test) / 2); i++) {
if (*(test + i) == *(test + (sizeof(test) - i)))
return 1;
else
return 0;
}
}
The Name of the array will itself acts as a pointer to an first element of the array, if you loose the pointer then there is no means for you to access the element of the array and hence you can send just the name of the array as a parameter to the function.
In the palindrome function:
you have used sizeof(test)/2. what happens is the address gets divided which is meaningless and hence you should not use that to calculate the mid element.
sizeof the pointer will be the same irrespective of the type of address that gets stored.
Why do you copy your pointer in another variable?
int *ptr;
ptr = &numArray[0];
Just send it to you function:
palindrome(numArray);
And sizeof(test) give you the memory size of a pointer, it's not what you want. You have to give the size in parameter of your function.
int palindrome(int *test, int size){
...
}
Finally your code must look like this:
#include<stdio.h>
int palindrome(int *test, int size);
int main()
{
int output;
int numArray[10] = {0,2,3,4,1,1,4,3,2,0};
output = palindrome(numArray, 10);
printf("%d", output);
}
//function determine if string is a palindrome
int palindrome(int *test, int size) {
int i;
for (i = 0; i < size / 2; i++) {
if (*(test + i) != *(test + (size - 1) - i))
return 0;
}
return 1;
}
I have written a program for insertion shot like following:
int _tmain(int argc, _TCHAR* argv[])
{
int arr[10] = {1,2,3,10,5,9,6,8,7,4};
int value;
cin >> value ;
int *ptr;
ptr = insertionshot(arr); //here Im passing whole array
BinarySearch(arr,value);
return 0;
}
int * insertionshot(int arr[])
{
//Changed after a hint (now, its fine)
int ar[10];
for(int i =0;i < 10; i++)
{
ar[i] = arr[i];
}
//Changed after a hint
int arrlength = sizeof(ar)/sizeof(ar[0]); //here array length is 1, it should be 10
for(int a = 1; a <= arrlength -1 ;a++)
{
int b = a;
while(b > 0 && ar[b] < ar[b-1])
{
int temp;
temp = ar[b-1];
ar[b-1] = ar[b];
ar[b] = temp;
b--;
}
}
return ar;
}
The problem is after passing the whole array to the function, my function definition only shows 1 element in array and also "arraylength" is giving 1.
int arr[] in a function formal parameter list is a syntax quirk, it is actually processed as int *arr. So the sizeof trick doesn't behave as you expect.
In C it is not possible to pass arrays by value; and furthermore, at runtime an array does not remember its length.
You could include the length information by passing a pointer to the whole array at compile time:
int * insertionshot(int (*arr)[10])
Of course, with this approach you can only ever pass an array of length 10. So if you intend to be able to pass arrays of differing length, you have to pass the length as another parameter.