Though we declare a function with an integer array, we pass address of the array to the function. In the case of simple integers it gives error if we pass address we get pointer conversion error. But how its possible in case of an array
#include<stdio.h>
void print_array(int array[][100],int x, int y);
main()
{
int i,j,arr[100][100];
printf("Enter the array");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&arr[i][j]);
}
}
print_array(arr,i,j);
}
void print_array(int array[][100],int x,int y)
{
int i,j;
printf("\nThe values are\n");
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
printf("%d",array[i][j]);
}
}
}
My question is even though our function is declared as one with integer array as first parameter (here) we are passing array address when we call the function. How does it function?
Your are passing the array, not its address.
arr is an int[][] array
(in fact it is pretty the same as &(arr[0]), which is a pointer to (the address of) the first line of your array. In C, there is no practical difference between an array and the corresponding pointer, except you take it's address with the & operator.)
Edit: Ok, just to make me clear:
#include <stdio.h>
int fn(char p1 [][100], char (*p2)[100])
{
if (sizeof(p1)!=sizeof(p2))
printf("I'm failed. %i <> %i\n",sizeof(p1),sizeof(p2));
else
printf("Feeling lucky. %i == %i\n",sizeof(p1),sizeof(p2));
}
int main()
{
char arr[5][100];
char (*p)[100]=&(arr[0]);
fn(arr, arr);
fn(p, p);
return 0;
}
Related
Im trying to understand pointers as function parameters, and in one of the programs there is a segmentation error I can't fix. Firstly, why to use pointers in function arguments? and Why is this error showing?
#include <stdio.h>
void square_it(int* a)
{
printf("The final value is: %d\n", *a * *a);
}
int main()
{
int* input;
puts("This program squares the input integer number");
puts("Please put the number:");
scanf("%d", &input);
square_it(input);
return 0;
}
int* input; does not allocate memory for an int. It mearly makes it possible to make input point at an int (allocated elsewhere). Currently, by dereferencing it (like you do with *a), you make your program have undefined behavior. If you really want an intermediate pointer variable for this, this example shows how it could be done:
#include <stdio.h>
void square_it(int *a) {
*a *= *a; // same as *a = *a * *a;
}
int main() {
int data;
int* input = &data; // now `input` points at an `int`
puts("This program squares the input integer number");
puts("Please put the number:");
// check that `scanf` succeeds:
if(scanf("%d", input) == 1) { // don't take its address, it's a pointer already
square_it(input);
// since `input` is pointing at `data`, it's actually the value of `data`
// that is affected by `scanf` and `square_it`, which makes the below work:
printf("The final value is: %d\n", data);
}
}
Without an intermediate pointer variable:
#include <stdio.h>
void square_it(int *a) {
*a *= *a;
}
int main() {
int input; // note that it's not a pointer here
puts("This program squares the input integer number");
puts("Please put the number:");
if(scanf("%d", &input) == 1) { // here, taking the address of `input` makes sense
square_it(&input); // and here too
printf("The final value is: %d\n", input);
}
}
Without any pointers at all, it could look like this:
#include <stdio.h>
int square_it(int a) {
return a * a;
}
int main() {
int input;
puts("This program squares the input integer number");
puts("Please put the number:");
if(scanf("%d", &input) == 1) { // here, taking the address of `input` makes sense
int result = square_it(input);
printf("The final value is: %d\n", result);
}
}
This is the working code:
#include <stdio.h>
void square_it(int* a)
{
printf("The final value is: %d\n", *a * *a);
}
int main()
{
int i = 0;
int* input = &i;
puts("This program squares the input integer number");
puts("Please put the number:");
scanf("%d", input);
square_it(input);
return 0;
}
There are some errors in the original code:
According to the man-pages to scanf, it takes a format string and then the address of where to store the input.
You gave it the address of a pointer (eg. an int**), which is not what scanf expects.
Also you need to provide memory to store the input in. The scanf string tells that you want an integer as input. In the above code snippet that is i.
input points to i, so i can give the int*, that is input to scanf. scanf will then write into i. We can then go ahead and put the address of i into the sqare_it function.
Since we did not use the heap, we don't need to worry about memory management.
So i'm trying to pass
char parent[n][50];
into a function initialize();
And then copy the char x, into the parent [ i ] inside the initialize(); function. Example
x = "Cityname"
and when passed into the initialize();
it would do
strcpy(parent[i], x);
to make the
parent[i] = "Cityname"
void initialize(char *parent, int *ranks, char x, int i){
strcpy(parent[i], x);
ranks[i] = '0';
}
int main(){
int n, i = 1;
char x[20];
printf("Enter how many city are there : "); scanf("%d", &n); fflush(stdin);
char parent[n][20];
int ranks[n];
while(1){
printf("enter city name: "); scanf("%[^\n]", x);
if(i <= n){
initialize(parent[][20], ranks, x, i);
i++;
} else {
printf("The city is at maximum\n");
}
}
}
It tells a warning:
passing argument 1 of 'strcpy' makes pointer from integer without a cast
note: expected 'char *' but argument is of type 'char'
and also in function main
error: expected expression before ']' token
Can anyone explain how to strcpy(parent[i], x) correctly? I can't seem to figure this problem out.
I see several problems with your code. Arrays vs pointers in C can be confusing, so there are a few rules to keep in mind:
char x[n] can be automatically converted by the C compiler to char *x.
char x[10][20] is represented under the hood as a 1D array, and the compiler computes the offsets behind the scenes. For example, if x were a 10 x 20 array, the expression x[1][2] could be compiled as *(x + 22). For this reason, it can cause surprising results to cast a 2D array to a char*, and it is invalid to cast a 2D array to a char**.
With these rules in mind, here is how I would change your code
void initialize(char (*parent)[20], int *ranks, char *x, int i){
strcpy(parent[i], x);
ranks[i] = '0'; // Did you want an automatic conversion from char to int here? Maybe you meant ranks[i] = 0?
}
int main(){
int n, i = 0; // As Craig mentions, i should start at 0.
char x[20];
printf("Enter how many city are there : "); scanf("%d", &n); fflush(stdin);
char parent[n][20];
int ranks[n];
while(1){
printf("enter city name: "); scanf("%19s", x); // scanf will automatically stop at whitespace, and you must include the max length to avoid a buffer overrun.
if(i < n){
initialize(parent, ranks, x, i);
i++;
} else {
printf("The city is at maximum\n");
// Maybe break here, unless you want an infinite loop
}
}
}
why am i getting this warning?the output was right as i wanted.this ia a simple pointer practice.But i am getting the unwanted warning.please help.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
main()
{
int a,b,c,i,j,k=0;
scanf("%d%d", &a, &b);
int arr[a][b];
int *ptr[b];
ptr[b]=arr;
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
*(*(arr+i)+j)=k;
k++;
}
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
printf("%d\t",*(*(arr+i)+j));
}
printf("\n");
}
return 0;
}
Because an array int [a][b] (2D int array) is not a compatible type with int* (int pointer). A 2D array when used in an expression decays to a pointer to the first element, which in this case would be an array pointer to a 1D array, of type int(*)[b].
The line ptr[b]=arr; therefore makes no sense and it also access the array ptr out of bounds.
If you wish to have a pointer to the first item in the 2D array, you would have to type
ptr[n] = &arr[0][0]; // where n is a value that makes sense
yes,I have figured it out.Now,i understand my mistake.
int* ptr[b];
ptr[b]=arr;
is totally wrong.In here I was declaring an array of "ptr" which is pointer to integer and was assigning a pointer "arr" to "ptr[b]" which is pointer to integer.as, arr is a 2D array it returns the address of arr[0][0] .but
ptr[b] is pointer to integer.so,these are not the same.(Actually,"ptr[b]=arr" doesn't make any sense.at first,I didn't understood it enough but now I have fixed it.
int (*ptr)[b];
ptr=arr;
Now it works without any warning.
I have changed the code as the following listing:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int a,b,i,j;
scanf("%d%d", &a, &b);
int *arr[a][b];
int *ptr[b];
int *k = 0;
ptr[b]=arr[a][b];
printf("\n%s%p","pointer = ",ptr[b]);
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
*(*(arr+i)+j)=k;
k++;
}
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
printf("%p\t",*(*(arr+i)+j));
}
printf("\n");
}
return 0;
}
This is the code :
#include <stdio.h>
int funk1()
{
int N=0;
float a;
FILE *f;
f=fopen("wyniki.txt", "r");
while(fscanf(f,"%f", &a)!=EOF)
{
N++;
}
fclose(f);
return N;
}
void funk2(int N, float T[][N])
{
FILE *f;
f=fopen("wyniki.txt", "r");
float a;
int i=0;
while(fscanf(f,"%f", &a)!=EOF)
{
T[i][0]=a;
T[0][i]=a;
printf("funk 2\n");
printf("liczba = %f i = %d \n", a, i);
printf("%f %f\n", T[i][0], T[0][i]);
i++;
}
fclose(f);
}
main()
{
int N = funk1();
float T[N][N];
funk2(N,T[][N]);
int i=0;
int j=0;
for(i=0;i<N;i++){
for(j=0;j<N;j++){
printf("|%f|\t",T[i][j]);
}
printf("\n");
printf("|%f|\t", T[i][j]);
}
getch();
return 0;
}
The problem is only with funk2. I want to pass the matrix (T) from main to funk2, do stuff with it and then give it back to main. I have no idea how to do that to be honest, I just tried out messing with it but it doesn't work. Any idea how to do that? Should I provide more information or is this enough? You can ignore the first function and the first half of funk2 as well. It all works just fine, the problem I have only has to do with passing the twodimensional array.
The result of this code is an error in
funk2(N,T[][N]);
(expected expression before ']' token).
Adding an N there results in
expected 'float (*)[(sizetype)(N)]' but argument is of type 'float'
The only time [] is valid syntax is when declaring an array either with an initializer or as a function parameter.
If you want to pass an array to a function, just pass it:
funk2(N,T);
You don't need to call out the dimensions of the array. The compiler knows it's an array.
I wrote a program
#include<stdio.h>
int *sqrt(int a[10]);
int main()
{
int a[10],i,*b;
printf("enter your integers \n");
for(i=0;i<10;i++)
scanf("%d",a+i);
b=sqrt(a[10]);
printf("the modulus of this values are\n");
printf("%d",*(b));
return 0;
}
int *sqrt(int x[10])// function
{
int *c,i;
for(i=0;i<10;i++)
{
x[i]=x[i]*x[i];
}
c=x;
return p;
}
The code gives me a segmentation fault after I enter the values. What mistake have I made here?
You are passing the 11th element to sqrt():
b = sqrt(a[10]);
You want to pass the address of the 1st element:
b = sqrt(&a[0]);
or even more straight forward:
b = sqrt(a);
Using the construct above the array a decays to a pointer to its 1st element, which is the same as &a[0].