Pointing to arrays using void function - c

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;
}
}

Related

leetcode 1st problem called two_sum im geting error,please help me with the mistake what i have done

this is my leetcode 1st day 1st problem called two_sum am getting an error, please help me with the mistake what I have done,
in vs code this, below code was getting no error and also no output, but in leetcode I getting an error :
Line 25: Char 5: error: conflicting types for ‘main’ [solution.c]
int main(int argc, char *argv[]) {
^~~~
where my code is only 22 lines but I was getting error in the 25th line
#include <stdio.h>
void main()
{
int n, a[10], i, j, t;
printf("enter the array size");
scanf("%d", &n);
printf("enter th array values");
for (i = 0; i < n; i++)
scanf("%d", &a[I]);
printf("enter the targest sum");
scanf("%d", &t);
for (i = 0; i < n; n++)
{
for (j = i+1; j < n; n++)
{
if (a[i] + a[j] == t)
{
printf("[%d,%d]", i, j);
}
}
}
}
2nd try: I replaced with a new code in the last if statement to check in another way. so, now I got output but, not the correct one
According to the C Standard the function main without parameters shall be declared like
int main( void )
Instead of the array with the fixed number of elements
int n, a[10], i, j, t;
you could use a variable length array like for example
int n, i, j, t;
printf("enter the array size");
scanf("%d", &n);
int a[n];
Another approach is to allocated the array dynamically like
int *a = malloc( n * sizeof( int ) );
You can write either each pair of values in a new line like
printf("[%d,%d]\n", i, j);
Or after all pairs you could print the new line character like
for (i = 0; i < n; n++)
{
for (j = i+1; j < n; n++)
{
if (a[i] + a[j] == t)
{
printf("[%d,%d] ", i, j);
}
}
}
putchar( '\n' );
{ay attention to that you have a typo
scanf("%d", &a[I]);
^^^
you need to write
scanf("%d", &a[i]);
^^^
Try declaring main as int main(int argc, char * argv[]) or int main(void). void main is usually not a valid type declaration so I presume both VS Code and Leetcode do not treat your main declaration as the entry to your program.
In leetcode, you don't need to (and should not) write your own main function. Leetcode has its own main function. Also you don't need to include libraries. What you need to do is just to implement the twoSum function.
Here's Leetcode's default code definition for the two sum problem:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
}
What you need to do is write code within the twoSum() function.
// don't need to #include<stdio.h>
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
// write your code here.
}
// don't need to write main function

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.

Can somone please explain this to me

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.

Pointers Run time error

I have used the below code for a simple operation
(to reverse a string). But the program is not executing. It gets a run time error (SIGSEGV) . I used a GCC compiler. Please help me in debugging the program.
#include <stdio.h>
#include <stdlib.h>
int *create(int n) {
int *a;
a = (int *)malloc(n * sizeof(int));
return a;
}
void get(int *a, int n) {
int i;
for (i = 0; i < n; i++) {
scanf("%d", *(a + i));
}
}
void reverse(int *a, int n) {
int i;
for (i = n - 1; i >= 0; i--) {
printf("\n %d", *(a + i));
}
}
int main() {
int n, *a;
scanf("%d", &n);
a = create(n);
get(a, n);
reverse(a, n);
return 0;
}
scanf("%d",*(a+i)); invokes undefined behavior because you passed int where int* is expected.
You must pass pointer to tell scanf() where to store the data read, so stop dereferencing and try using scanf("%d",(a+i)); instead.
More notes are:
You should check if readings are successful.
They say you shouldn't cast the result of malloc() in C.

Troubles with arrays in c

So I am currently getting into programming and I'm trying to write this code, but I am having trouble with arrays. I have read a lot of articles online and it seems that this code should work, but for some reason there is an error when I pass my arrays between my functions. Ignore the commented out section in the middle that is where I got it to work inside my main function. For this assignment I need it to work in the functions I defined below. I am just wanting to initialize my array in one function then print it out in the other.
Thanks!
here is the error it displays
prelab7.c:32: warning: passing argument 1 of ‘print_array’ makes pointer from integer without a cast
prelab7.c:7: note: expected ‘int *’ but argument is of type ‘int’
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int errorcheck(int );
void intializearrary(int[], int);
void print_array(int [], int);
int main()
{
int maxsize,i;
int n[maxsize];
printf("\nEnter the size of the input: ");
scanf("%d", &maxsize);
while (errorcheck (maxsize))
{
printf("\nInvalid input enter the size of the input again");
scanf("%d", &maxsize);
}
/* srand(time(NULL));
for (i = 0; i < maxsize; i++)
{
n[i] = generaterandomnumber();
printf("\nn[%d]=%d", i, n[i]);
}
*/
print_array( n[i], maxsize);
return 0;
}
int errorcheck (int maxsize)
{
if (maxsize < 0 || maxsize > 100)
return 1;
else
return 0;
}
void initializearrary( int n[],int maxsize )
{
int i;
srand(time(NULL));
for (i = 0; i < maxsize; i++)
{
n[i] = rand()%10;
}
}
void print_array(int n[], int maxsize)
{
int i; //counter
printf("\nInput Array\n");
for (i = 0; i < maxsize; i++)
{
{
printf("\t%d", n[i]);
}
}
/*int generaterandomnumber()
{
return rand()%10;
}*/
Move
int n[maxsize];
Just after the while loop and change
print_array( n[i], maxsize);
To
print_array( n, maxsize);
The former is done so that maxsize gets initialized before the VLA is constructed.
The latter is done because print_array expects an int* as the first argument, but you pass an invalid argument n[i] which is of type int.

Resources