Pass by reference in c array - c

Hi i want to ask about why i need to use printf("\n%d",x); instead of printf("\n%d",*x);?
Thank you very much
#include<stdio.h>
#include<stdlib.h>
#define totalnum 8
void display(int **);
int main()
{
int marks[totalnum]={55,65,75,85,90,78,95,60};
printf("The marks of student A are:");
display(marks);
return 0;
}
void display(int *x)
{
int i;
for(i=0;i<totalnum;i++)
printf("\n%d",x);
}

There is no pass by reference in C. The array decays to a pointer in the display function which you declared wrongly as int ** instead of int * - Compiler should have given you a warning at least about this:
http://ideone.com/R3skNj
This is how your display function should be like:
void display(int *x)
{
int i;
for(i = 0; i < totalnum; i++) {
printf("\n%d",*(x+i)); // or printf("\n%d",x[i]);
}
}

I think your looking for something like this:
#include <stdio.h>
#include <stdlib.h>
#define totalnum 8
void display(int *); //Typ is 'int *' NOT 'int **'
int main() {
int marks[totalnum] = {55,65,75,85,90,78,95,60};
printf("The marks of student A are:");
display(marks);
return 0;
}
void display(int *x) {
int i;
for(i = 0; i < totalnum; i++) {
printf("\n%d",*x); //Prints the value
x++; //increments the pointer
}
}

Related

Passing an array from a struct as an argument to a function

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
int votes;
}
candidate;
void array_function(int arr[]);
int main(void)
{
candidate candidates[3];
candidates[0].votes = 5;
candidates[1].votes = 3;
candidates[2].votes= 1;
print_array_function(candidates.votes);
}
void print_array_function(int arr[])
{
for (int i = 0; i < 3; i++)
{
printf("%i\n", arr[i]);
}
}
I'm trying to run this code which declares a struct, feeds values into it and tries to pass an array inside the struct to a function. However, on doing so I get the following error:
test.c:22:30: error: member reference base type 'candidate [3]' is not a structure or union
array_function(candidates.votes);
How do I pass this structs array into the function?
Just declare the function like
void array_function( const candidate arr[], size_t n );
and call like
print_array_function( candidates, 3 );
The function can be defined the following way
void array_function( const candidate arr[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
printf( "%i\n", arr[i].votes );
}
}
Here, you have an array of structure candidate which each element contains a single int called votes (certainly vote would be a better name for it). Maybe the best approach to do what you want is to create a function print_candidate_array_vote as :
void print_candidate_array_vote(candidate *candidates, unsigned int n_candidates)
{
for (int i = 0; i < n_candidates; i++) {
printf("%d\n", candidates[i].votes);
}
}
Try the code below, have made some changes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct candidate
{
int votes;
}
candidate;
void array_function(int arr[]);
int main(void)
{
candidate candidates[3];
candidates[0].votes = 5;
candidates[1].votes = 3;
candidates[2].votes= 1;
print_array_function(candidates);
}
void print_array_function(candidate arr[])
{
for (int i = 0; i < 3; i++)
{
printf("%i\n", arr[i]);
}
}

Warning parameter names [When I try to load my array

So I'm getting this message when I try to load my array using pointers.
I don't know why this keep appearing since the last program had no problem
#include<stdio.h>
#define T 10
void FLoad(int *);
void main () {
int a[T];
void FLoad(a);
}
void FLoad(int *a) {
int x;
for (x = 0; x < T; x++)
scanf("%d", a+x);
}
And here is a little program that works perfectly
#include <stdio.h>
void FImp(int *, int );
main () {
int a[] = {-10,-5,3,4}, tam;
tam = sizeof(a) / sizeof(int);
FImp(a, tam);
}
void FImp(int *a, int t) {
int x;
for (x = 0; x < t; x++)
printf("%d ",*(a + x));
putchar('\n');
}
You are using incorrect syntax when calling your function
void main()
{
int a[T];
void FLoad(a);
}
should be
void main()
{
int a[T];
FLoad(a);
}
or even better
int main(void)
{
int a[T];
FLoad(a);
}
You don't specify the function return value when you call it.
void FLoad(a);
This won't call the function. The compiler will consider this as a function declaration. So call the function without void it will work fine.

C: Printing out the value and memory location of each element of an array using pointers?

I have generated a random array inside the main function, How can I properly print it out using a separate function and inside the function print out the value and memory location of each element of that array using pointers. Here is my code so far:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void printArray(int *pointertoArray, int *Size);
int main (void)
{
srand(time(NULL));
int array[10];
int *pointer = NULL;
for(int i = 0; i < size; i++)
{
array[i] = rand();
*pointer = array[i];
printArray(*pointer,size);
}
}
void printArray(int *pointerToArray, int *size)
{
int i = 0;
do
{
printf("\nValue %d = %p ",i,*pointerToArray);
i++;
}
while(i < size);
}
Here is what I am trying to achieve:
value 1 = 0x7fff0815c0e0
.....
value 10 = 0x7fff0815c0ec
int *size should be int size. You don't pass a pointer, and you don't need a pointer.
Actually, size_t size would be more appropriate.
The call to printArray should be located after the loop. You only want to print the array once.
printArray(*pointer, size); should be printArray(array, size);.
pointerToArray should be named array or pointerToInts.
The value of the element is pointerToArray[i], not i.
The address of the element is pointerToArray+i, not *pointerToArray.
The loop in printArray should be top-tested. (No reason for it to be bottom tested, so play it safe.)
main is declared to return an int, but doesn't.
We get,
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void printArray(int *array, size_t size);
int main() {
srand(time(NULL));
int array[10];
for (int i = 0; i < size; ++i) {
array[i] = rand() % 1000;
}
printArray(array, sizeof(array)/sizeof(array[0]));
return 0;
}
void printArray(int *array, size_t size) {
for (int i = 0; i < size; ++i) {
printf("Value # %p = %d\n", array+i, array[i]);
}
}
Alternative:
void printArray(int *pointerToInt, size_t size) {
for (; size--; ++pointerToInt) {
printf("Value # %p = %d\n", pointerToInt, *pointerToInt);
}
}

how to persist the pointer increment

I have the following code
void fun(int * d)
{
d+=1;
}
int main()
{
int * f=malloc(5);
f[0]=0;f[1]=1;f[2]=2;f[3]=3;f[4]=4;
fun(f);
printf("value : %d\n",*f);
return 0;
}
So, i pass an integer pointer to function and increment it there. I want that increment to persist when it returns to main.
When I print the value, The output is '0'. But I want the output to be '1' as I have incremented the value in function.
So, briefly, my question is, how to persist the changes made to a pointer?
Assuming you want to increment the pointer, not the value, you have two options:
recast the function to void fun(int ** d), use (*d)+=1; in the function body, and call using fun(&f);
recast the function to int* fun(int* d), and return the new value.
If you want to increase the value, then use (*d)+=1; in the function body.
You don't need the parentheses around *d: I've put them in for clarity.
You forgot * in d+=1;
When you pass that pointer you have access to f[0] with that approach:
Take a look here:
#include <stdio.h>
#include<stdlib.h>
void fun(int *d){
*d+=1;
}
int main(void){
int i;
int *f=malloc(5 * sizeof int);
f[0]=0;f[1]=1;f[2]=2;f[3]=3;f[4]=4;
for(i=0;i<5;i++){
printf("%d ",f[i]);
}
printf("\n");
fun(f);
for(i=0;i<5;i++){
printf("%d ",f[i]);
}
free(f);
return 0;
}
Output:
0 1 2 3 4
1 1 2 3 4
Or if you try to add +1 to all elements you can do something like this:
#include <stdio.h>
#include<stdlib.h>
int *fun(int *d, int len){
int i;
int *newArray = d;
int newValue = 1;
printf("\n");
for(i = 0; i < len; i++) {
newArray[i] += newValue;
}
return newArray;
}
int main(void){
int i;
int f[] = {0,1,2,3,4};
int *newArray;
f[0]=0;f[1]=1;f[2]=2;f[3]=3;f[4]=4;
for(i=0;i<5;i++){
printf("%d ",f[i]);
}
printf("\n");
newArray = fun(f,5);
for(i=0;i<5;i++){
printf("%d ",newArray[i]);
}
return 0;
}
Output:
0 1 2 3 4
1 2 3 4 5
And by the way you forgot to free f.
You have to pass the address of the pointer, so:
void fun(int **val) {
*val++;
....
}
int main() {
...
fun(&f);
...
}

Passing array to function using pointer

I'm trying to print array of pointer using pointer instead of array but I got this error Segmentation fault at runtime:
enter number of element:5
array[0]=1
array[1]=2
array[2]=3
array[3]=4
array[4]=5
Segmentation fault
This is the code:
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int *array,int n);
void display(int *array,int n);
int sum(int *array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(array,n);
display(array,n);
result=sum(array,n);
printf("sum of array=%d",result);
return 0;
}
void input(int *array,int n){
int j;
array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",array+j);
}
}
void display(int *array,int n){
int j;
for(j=0;j<n;j++)
printf("%d\t",*(array+j));
printf("\n");
}
int sum(int *array,int n){
int sum=0,j;
for(j=0;j<n;j++)
sum+=*array+j;
return sum;
}
How can I fixed this code? please somebody explain me what's wrong with that code.
Variable array is a local variable in function input.
As such, it is pointless to set it with array = ..., because this assignment takes effect only inside the function. You should typically pass its address (&array) to any function that needs to change it.
In your specific example, you also have a global variable array, so a quick solution to your problem would be to simply call function input without passing variable array as an argument:
void input(int n)
{
...
array = (int*)malloc(n*sizeof(int));
...
}
int main()
{
...
input(n);
...
}
Note that this is a "dirty" workaround, and you should typically strive to avoid the use of global variables.
To add the clean version to barak's answer:
int input(int ** array, const size_t n)
{
int result = 0;
assert(NULL != array);
(*array) = malloc(n * sizeof(**array));
if (NULL == (*array))
{
result = -1;
}
else
{
size_t j;
for(j = 0; j < n; ++j)
{
printf("array[%zu]=", j);
scanf("%d", (*array) + j); /* still missing error checking here . */
}
}
return result;
}
And call it like this:
if (-1 == input(&array, n))
{
perror("input() failed");
exit(EXIT_FAILURE);
}
Try this input():
void input(int **array,int n){
int j;
*array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",*array+j);
}
}
Because C use pass-by-value, if you want to change the value of a variable in a function, you need to pass the address of that variable as the argument to that function.
In this case, you want to change the value of array in input() and the type of array is int *, therefore the prototype of input() should be something like void input (int **array, ...).
this should do..make sure you understand what the others have said..
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int **array,int n);
void display(int **array,int n);
int sum(int **array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(&array,n);
display(&array,n);
result = sum(&array,n);
printf("sum of array= %d",result);
return 0;
}
void input(int **array,int n){
int j;
*array= malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);
scanf("%d",(*array)+j);
}
}
void display(int **array,int n){
int j;
for(j=0;j<n;j++){
printf("%d\t",*((*array)+j)); // you can use array notation aswell
//array[0][j] will work
}
printf("\n");
}
int sum(int **array,int n){
int sum=0,j;
for(j=0;j<n;j++){
sum += *((*array)+j);
}
return sum;
}
What does *array + j do? Does it evaluate *array and add j to it? Or does it add j to array and then dereference it? Would you be willing to bet $100 on it if I told you you are wrong?
Make your life and the life of anybody reading your code easier by using parentheses, or even better, write array [j].

Resources