i get some problems with scanf() in C [duplicate] - arrays

This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 8 months ago.
#include <stdio.h>
#include <stdlib.h>
void add(int *arr, int n);
int main() {
int arr[] = {};
add(arr, 4);
return 0;
}
void add(int *arr, int n){
for (int i = 0; i < n; i++){
printf("%d index is : ", i);
scanf("%d\n", &arr[i+1]);
}
}
the for loop doesn't work after the i == 1... the execution stops and then I have to press some alphabet and executes the whole for loop with no values...

This declaration in C and in C++
int arr[] = {};
is invalid. The initializer list shall not be empty.
Instead you could write in C
int arr[4] = { 0 };
or
int arr[] = { [3] = 0 };
And within the function instead of
scanf("%d\n", &arr[i+1]);
^^^
you have to write
scanf("%d", &arr[i]);
^^^
Otherwise there will be an access to memory outside the array.

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.

Read 2D Array of String in C [duplicate]

This question already has answers here:
Memory overwrite problem
(4 answers)
Closed 5 years ago.
I am trying to create a 2D array of chars from some input on the keyboard.My main problem is that I don't know what I am doing wrong but I am able to get a result when I go above the length of the array. For example if I have a n x n matrix, i can print the value x[0][n] or x[0][n+1]. I just want to know what am I doing wrong as I should get an error as I am trying to go over the bound of the array.
#include <stdio.h>
#include <stdlib.h>
void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}
char ** readMatrix(int m){
char **arr = safeMalloc(m*sizeof(char *));
int row;
for (row=0; row < m; row++) {
arr[row] = safeMalloc(m*sizeof(char));
}
int i,j;
for(i=0;i<m;i++){
for(j=0;j<m;j++){
scanf(" %c",&arr[i][j]);;
}
getchar();
}
return arr;
}
void printNumber(char **arr,int m){
int i,j;
for(i=0;i<m;i++){
for(j=0;j<m;j++){
printf("%c", arr[i][j]);
}
printf("\n");
}
}
int main(int argc, char **argv)
{
int n;
scanf("%d",&n);
char** arr;
arr=readMatrix(n);
printf("%c\n",arr[0][8]);
printNumber(arr,n);
}
For example :
8
****....
****....
****....
****....
........
........
........
........
It prints the array as I expected but I can still get some funny char if I go over the bound 8.
Since C doesn't check array boundaries thats why you are not getting error but getting funny characters by accessing memory past the end of the array.

pointer in function don't return correct address [duplicate]

This question already has answers here:
How to change value of variable passed as argument?
(4 answers)
Why does not the value of the pointer passed to the function change? [duplicate]
(2 answers)
Closed 5 years ago.
I try to make a function that allocates an array in C
and I don't get the right address.
this is the code:
#include <stdio.h>
#include <stdlib.h>
void allocate_array(int* arr, int size);
void print_array(int* arr, int size);
void main(){
int size;
int* arr;
printf("Please enter array size: ");
scanf("%d", &size);
allocate_array(arr, size);
print_array(arr, size);
}
void allocate_array(int* arr, int size){
int i;
arr = (int*)malloc(size*sizeof(int));
for(i=0; i<size; i++){
printf("arr[%d] = ",i);
scanf("%d", arr+i);
}
}
void print_array(int* arr, int size){
int i;
printf("\n");
for(i=0; i<size; i++){
printf("arr[%d] = %d\n", i, *(arr+i));
}
}
and this is the output that I get:
Please enter array size: 4
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[0] = 1
arr[1] = 0
arr[2] = 155039806
arr[3] = 32765
I tried to print the pointer in "allocate_array" function
and in the "main" but I get different result.
Please help :)
Thanks!

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

how to get the correct input value from the pointer [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 8 years ago.
I want to use a function that receive a pointer to an array together with its size and sets all element value to zero.
But the value of the array was checked in the function, the value is not 1234 which should be 1234 if correct, because the input value is 1234.
Just want to know where's the mistake in my following code.
#include <stdio.h>
#include <stdlib.h>
void receive(int *point, const int size);
int main(void) {
int a;
int *b;
scanf("%d", &a);
b=(int*)malloc(sizeof(int)*a);
printf("size of input: %d\n", sizeof(b));
receive(b, sizeof(b));
free(b);
return 0;
}
void receive(int *point, const int size) {
int c=sizeof(*point);
printf("filling the array to zero");
int i;
for (i=0; i<c; i++) {
printf("\n previous_value:%d\n", point[i]);
point[i]=0;
printf(", current_value %d\n", point[i]);
}
}
I changed a few incorrect statements, the resulting code is:
#include <stdio.h>
#include <stdlib.h>
void receive(int *point, const int size);
int main(void) {
int a;
int *b;
scanf("%d", &a);
b= malloc(sizeof(int)*a); //removed implicit declaration of malloc return value
printf("size of input: %d\n", a);
receive(b, a); //changed sizeof(b) to a as second argument of function
free(b);
return 0;
}
void receive(int *point, const int size) {
//removed int c = sizeof(*point); unnecessary statement
printf("filling the array to zero");
int i;
for (i=0; i<size; i++) { //substituted c with size
printf("\n previous_value:%d\n", point[i]);
point[i]=0;
printf(", current_value %d\n", point[i]);
}
}

Resources