Function printArray not working properly - c

I'm trying to make function that prints array but the output of it is wrong.
Can someone help me please?
This is the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void printArr(int arr[],int size);
int main()
{
int arr1[3] = { 1,2,3 };
int arr2[5] = { 1,2,3,4,5 };
printf("arr1: \n");
printArr(arr1, 3);
printf("\n\narr2: \n");
printArr(arr2, 5);
printf("\n\n");
return(0);
}
void printArr(int arr[], int size)
{
int i;
for (i = 0; i < size; i++);
{
printf("%d", arr[i]);
}
}
What I get is:

Remove the semi-colon at the of for:
for (i = 0; i < size; i++);
^^^
That makes the for loop run size times and executes the block after that. But by that time, i value is equal to size. This leads to out of bound access, which is undefined behaviour. Clearly, this is not what you intention was.

Related

why does my program print garbage values when i try using recursion?

i'm new to programming and i'm learning about recursion, i am doing exercise 4 from this page
https://www.w3resource.com/c-programming-exercises/recursion/index.php, i am trying to print the elements of the array once the value of "i" in the recursive function gets to the value of "n", however once i run the program it prints garbage values i think.my question is why does it do that? why doesn't it print the values of the array?
#include <stdio.h>
#include <stdlib.h>
void printr(int n,int i);
int main (void)
{
printf("NUMBER OF ELEMENTS:\n");
int n;
scanf("%i",&n);
printr(n,0);
}
void printr(int n,int i)
{
int arr[n];
if (i == n)
{
for (int j = 0; j < n; j++)
{
printf("%d",arr[j]);
return;
}
}
printf("element %d :\n",i+1);
int e;
//scan for input
scanf("%d",&e);
//populate array
arr[i]=e;
//do it again
printr(n,i + 1);
}
Then i solved it by passing the array defined in the mein function asan argument in the printr function
it worked but i don't understand why my first attemp didn't?
#include <stdio.h>
#include <stdlib.h>
void printr(int arr[],int n,int i);
int main (void)
{
printf("NUMBER OF ELEMENTS:\n");
int n;
scanf("%i",&n);
int arr[n];
printr(arr,n,0);
}
void printr(int arr[],int n,int i)
{
if (i == n)
{
for (int j = 0; j < n;j++)
{
printf("%d ",arr[j]);
}
printf("\n");
return;
}
printf("element %d :\n",i+1);
int e;
//scan for input
scanf("%d",&e);
//populate array
arr[i] = e;
//do it again
printr(arr,n,i + 1);
}
Thank you!
Because basic C: each invocation of printr has its own arr on the stack, initially uninitialized. And you print it without initializing it first.
When you print out the value, it isn't initialized first. When you create the variable to be printed, its pointing to a place in memory. This memory was probably freed by another program (so its up for grabs). As such, it contains "garbage" data. The way to deal with this is to initialize your values.
In order to avoid stuff like this in the future, get in the habit of setting your pointers to NULL when you don't initialize them so that your programs segfaults when your trying to read an uninitialized value.

Trying to write a program to fill an array with random numbers in C

My issue is that I am getting segmentation fault (core dumped) each time I try, I have yet to clean up my code, but I am stumped.
I must enter the values in with the compiler e.g "./filename 0 100" whereby 0 is min and 100 is max.
It must then fill the array of 10 elements with random numbers (0-100). I am so close, just can't fathom the main function.
Also, how can I print the array {0,1,2,3} in format "[0,1,2,3]" including the commas, without it looking like "[0,1,2,3, ]"
#include <stdlib.h>
#include <stdio.h>
int getRandom(int min, int max);
void fillArray(int data[], int size, int min, int max);
void printArray(int data[], int size);
int main(int argc, char *argv[]) {
int a;
int b;
if (argc>=3){
a = atoi(argv[1]);
b = atoi(argv[2]);
int arr[10];
printf("\t An array with random values from 0 to 100 \n");
fillArray(arr,10 ,a, b);
printArray(arr, 10);
} else {
printf("Incorrect number of arguments - please call with assignment min max\n");
}
return 0;
}
int getRandom(int min, int max) {
int result = 0;
int low = 0;
int high = 0;
if (min<max) {
low = min;
high = max+1;
} else {
low = max + 1;
high = min;
}
result = (rand() % (high-low)) + low;
return result;
}
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){
data[i] = getRandom(min,max);
}
}
void printArray(int data[], int size){
int i;
printf("[");
for(i=0; i<size; i++){
printf("%d,", data[i]);
}
printf("]");
}
I agree with #Steve Friedl that the main problem with your program lies in the fillArray function. There i should run from 0 to size.
As for your second question, testing whether you're printing the last number helps to suppress the unwanted comma:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d", data[i]);
if (i < size - 1)
printf(",");
}
printf("]");
}
If you prefer a more compact solution (although with an optimizing compiler there's not really a difference), you could write it as:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d%c", data[i], i < size-1 ? ',' : ']');
}
}
Also, in your main function, you should include a and b in your printing:
printf("\t An array with random values from %d to %d \n", a, b);
I believe this is blowing things up for you:
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){ // <-- HERE
data[i] = getRandom(min,max);
}
}
The calling function allocates 10 items in the arr array, and that's passed as the size parameter, but you're not using that parameter to limit filling up the array. If the max value is 100, then it's trying to fill one hundred slots instead of just ten.
for (i = 0; i < size; i++)
data[i] = getRandom(min,max);
should fix at least this issue.
EDIT: The comma thing, I prefer to add commas before the items unless this is the first. In this case it doesn't matter much, but it's more general, especially for variable-length lists where you don't know you're at the end until you get there. Augmenting the helpful response from #JohanC :
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
if (i > 0) printf(",");
printf("%d", data[i]);
}
printf("]");
}

c code to print reverse of array using recurion

This code is to print reverse of array using recursion
I am using recursion function called from main
output should be as 5,4,3,2,1
can someone help in debugging this
#include <stdio.h>
void recursion(int a[])
{
int i=0;
if(i<5)
return;
i++;
recursion(i);
printf("%d ",a[i]);
}
int main()
{
int arr[]={1,2,4,5};
recursion(arr);
}
A good C book is needed:
#include <stdio.h>
void recursion(int a[], int i, int size)
{
if(i < size -1)
recursion(a, i + 1, size);
printf("i = %d arr[%d] == %d \n",i, i, a[i]);
}
int main()
{
int arr[] = {1, 2, 4, 5};
recursion(arr, 0, sizeof(arr) / sizeof(arr[0]));
}
Your recursion function is not working properly.
Note whenever you are calling a function the parameters should be same. In your code parameter of your function is array, but when you are calling it from inside the function i.e recursion you are passing i.
So, what you can do is that
#include <stdio.h>
void recursion(int a[], int i)
{
int t = i-1;
if(t>=0)
{
printf("%d ",a[t]);
return recursion(a, t);
}
}
int main()
{
int arr[]={1,2,4,5};
recursion(arr,4);
}
Hopefully that helps

Pointing to arrays using void function

Sorry for that title. I really didn't know how to define this problem.
I was needed to declare integer array of N numbers and to fill it with random nums in void function. Then that array needs to be printed in main. The thing is that i am not allowed to use printf in void function so only way to print in main is to use pointers I guess. My knowledge is limited as I am beginner at pointers. Thx in advance and sorry for bad english.
Here is my code so far. When I compile it marks segmentation error.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form();
int main()
{
int N, a[100];
printf("Input index: \n");
scanf("%d", &N);
form(N, &a);
printf("Array: \n");
for (int i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr[100])
{
srand(time(NULL));
for (int i = 0; i < N; i++) {
*ptr[i] = rand() % 46;
}
There are several issues in your code.
1) Your array decalaration form() is obsolete. Use proper prototype.
2) For declaring a VLA, declare it after reading N instead of using a fixed size array.
3) An array gets converted into a pointer to its first element when passed to a function. See: What is array decaying?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form(int, int*); /* see (1) */
int main(void) /* Standard complaint prototype for main.
If you need to pass arguments you can use argc, and argv */
{
int N;
printf("Input size: \n");
scanf("%d", &N);
int a[N]; /* see (2) */
form(N, a); /* see (3) */
printf("Array: \n");
for (int i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr) { /* Modified to match the prototype
srand(time(NULL));
for (int i = 0; i < N; i++) {
ptr[i] = rand() % 46;
}
}
So a couple things:
void form();
As Olaf was alluding to, this declaration is incorrect - you are missing the applicable parameters. Instead, it should be
void form(int N, int ptr[100]);
The main reason your program is crashing is because of the following line:
*ptr[i] = rand() % 46;
You are dereferencing the pointer at i, which is actaully giving you a number - what you want is to assign the value of the pointer at i the new random value:
ptr[i] = rand() % 46;
As related reading, see this question about passing an array in as a function parameter (basically, int ptr[] is the same thing as int * ptr)
Small modifications on your code:
1) Correction and simplification of parameter handling at function call. Just hand over "a", it's an array, so it is an address, you can use int *ptr, or int ptr[], or int ptr[100] in the formal parameter list for it. So you can use simply ptr[i] in your function.
2) Make a prototype for function from old-style declaration providing parameter list.
3) int i; declaration before the for loop - not mandatory, depends on your compiler standard
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form(int N, int *ptr);
int main()
{
int N, a[100];
printf("Input index: \n");
scanf("%d", &N);
form(N, a);
printf("Array: \n");
int i;
for (i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr)
{
srand(time(NULL));
int i;
for (i = 0; i < N; i++) {
ptr[i] = rand() % 46;
}
}

Program in c with functions without pointers doesn't work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have written a code and it doesn't run. However, there are no mistakes in compiler. I am stuck, could you give me a hint please where am I wrong?
I am 95% sure it is about checktable function.
P.S. I know how to do it with pointers, but I try to understand how to make it without them.
Thank you!
#include <stdio.h>
#include "genlib.h"
void fillarray (int a[50])
{
int i;
for(i=0;i<50;i++)
a[i]=rand()%10;
}
void printarray (int a[50])
{
int i;
for(i=0;i<50;i++)
printf(" %d ", a[i]);
}
int number()
{
int num;
printf("Give the number!");
num=GetInteger();
return num;
}
void checktable (int a[50], int b[50], int ar,int count)
{
int i;
count=0;
for(i=0;i<50;i++)
if (a[i]==ar)
{
b[count]=i;
count++;
}
}
main()
{
int i,a[50], b[50], N,count;
fillarray(a);
printarray(a);
N=number();
checktable(a,b,N,count);
printf("the number is used %d times", count);
printf("in places:");
for(i=0;i<count;i++)
printf("%d ",b[i]);
getch();
}
Approach 1: The "pointer" way:
In your code, change
void checktable (int a[50], int b[50], int ar,int count)
to
void checktable (int a[50], int b[50], int ar,int *count)
and call it as checktable(a,b,N,&count);
Approach 2: The "return" way:
Otherwise, the count which is updated in checktable() won't be reflected in main().
However, Alternatively (without using pointers), IMO, its always easier to simply return the number of occurrences via return statement. In that case , code will look like
int checktable (int a[50], int b[50], int ar)
{
int i;
int count=0;
for(i=0;i<50;i++)
if (a[i]==ar)
{
b[count]=i;
count++;
}
return count;
}
and the calling will be
count = checktable(a,b,N);
Note: Its always a good practice to initialize your variables.
If you don't want to use pointers,then you can return count and assign it to the count variable in main. I've improved your code here with all of it explained in the comments inside the code:
#include <stdio.h>
#include <stdlib.h> //Don't forget this header for srand and rand
#include <time.h> //For the time in srand
#include <conio.h> //For using getch()
#include "genlib.h"
void fillarray (int a[]) //leave the brackets empty
{
int i;
for(i=0;i<50;i++)
a[i]=rand()%10;
}
void printarray (int a[]) //here too
{
int i;
for(i=0;i<50;i++)
printf(" %d ", a[i]);
}
int number()
{
int num;
printf("\n\nGive the number!");
num=GetInteger();
return num;
}
int checktable (int a[], int b[], int ar) //Use int to return an int
//No need for count parameter
{
int i,count;
count=0;
for(i=0;i<50;i++)
if (a[i]==ar)
{
b[count]=i;
count++;
}
return count; //returning count
}
int main() //Use int main
{
int i,a[50], b[50], N,count;
srand(time(NULL)); //For rand to generate random numbers
fillarray(a);
printarray(a);
N=number();
count=checktable(a,b,N); //set count to the return value of checktable
//Also,no need to pass count as a parameter
printf("The number is used %d times", count);
printf(" in places:");
for(i=0;i<count;i++)
printf("%d ",b[i]+1); //Don't forget +1 otherwise output might come as place 0
getch();
return 0; //main returns int
}

Resources