Passing multidimensional arrays by void functions - c

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.

Related

When calling a function, why do I get these errors?

I get these warnings that I believe are preventing anything from printing:
"passing argument 1 of 'printboard' makes pointer from integer without a cast" when I call the function and "expected char(*)[26] but argument is of type 'char'" on line 2.
#include <stdio.h>
void printBoard(char board[26][26], int n){
int i,j,k;
if (i=0){
for (j=1;j<n;j++){
for (k=1;k<n;k++){
board[i][j]=k;
}
printf("%c", k+96);
}
}
if (j=0){
for(i=1;i<n;i++){
for(k=1;k<n;j++){
board[i][j]=k;
printf("%c", k+96);
}
}
}
for (i=1;i<=n;i++){
for (j=1;j<=n;j++){
if (board[i][j]!=board[n/2][n/2]&&board[i][j]!=board[(n/2)+1][(n/2)+1]&&board[i][j]!=board[n/2][(n/2)+1]&&board[i][j]!=board[(n/2)+1][n/2]){
board[i][j]='U';
}
else if (board[i][j]==board[n/2][n/2]&&board[i][j]==board[(n/2)+1][(n/2)+1]){
board[i][j]='W';
}
else {
board[i][j]='B';
}
}
printf("%c", board[i][j]);
}
//n is even
return;
}
int main(void)
{
const char board[26][26];
int dim;
char boardConfig;
printf("Enter the board dimension: \n");
scanf("%d", &dim);
printBoard(board[26][26],dim);
board[26][26] is a char element (out of bounds). You want to pass the entire 2D array board:
printBoard(board,dim);
(also: check return code of scanf, and check if dim is within 1-26 bounds to avoid undefined behaviour)
And when initializing board[i][j]=k; add some ASCII offset (ex: board[i][j]=k+'a';). Otherwise, your code will print non-ASCII characters at the end.
You need to typecast it to the parameter type. There are a number of errors in your code - such as the assignment operators instead of comparison operators. if(i=0) should be if(i==0), etc. I got the code compiled and working, not certain as to what you are trying to do yet, but this should work:
#include <stdio.h>
void printBoard(char board[26][26], int n){
int i = 0;
int j = 0;
int k = 0;
if (i==0){
for (j=1;j<n;j++){
for (k=0;k<n;k++){
board[i][j]=k;
}
printf("%c", k+96);
}
}
if (j==0){
for(i=1;i<n;i++){
for(k=0;k<n;k++){
board[i][j]=k;
printf("%c", k+96);
}
}
}
for (i=1;i<=n;i++){
for (j=1;j<=n;j++){
if (board[i][j]!=board[n/2][n/2]&&board[i][j]!=board[(n/2)+1][(n/2)+1]&&board[i][j]!=board[n/2][(n/2)+1]&&board[i][j]!=board[(n/2)+1][n/2]){
board[i][j]='U';
}
else if (board[i][j]==board[n/2][n/2]&&board[i][j]==board[(n/2)+1][(n/2)+1]){
board[i][j]='W';
}
else {
board[i][j]='B';
}
}
printf("%c", board[i][j]);
}
//n is even
return;
}
int main(void)
{
const char board[26][26];
int dim;
char boardConfig;
printf("Enter the board dimension: \n");
scanf("%d", &dim);
printBoard((char (*)[26])board,dim);
}

Problem in C : How to properly call function inside main

So there is this project in Data Structures that i have to deal with this semester and it requires that i have to code in C . The problem is that i am a little bit rusty in C and i am dealing with basic problems. One of the problems is that i have to write a simple program in C that implements BubbleSort . The BubbleSort algorithm has to be a seperate function and call it in the main program . Here is my effort . The problem is that it doesnt type the sorted array . I hope you can help me .
THE CODE :
int calculateRand()
{
int num;
num = (rand())%(UPPER-LOWER+1)+LOWER;
return num;
}
void swap(int *xp, int *yp)
{
int temp=*xp;
*xp=*yp;
*yp=temp;
}
void BubbleSort(int S[], int n)
{
int up=n;
int i,j;
while(up>1)
{
j=0;
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
}
for(i=0; i<n; i++)
{
printf("%d\n", S[i]);
}
}
int main()
{
int n,i;
printf("Parakalw dwste mia timh sto n: \n");
scanf("%d", &n);
int S[sizeof(n)];
printf("O mi taxinomimenos pinakas einai o exis \n");
for(i=0; i<n-1; i++)
{
S[i]=calculateRand();
printf("%d\n", S[i]);
}
printf("O pinakas meta thn taxinomisi einai \n");
BubbleSort(S[sizeof(n)], n);
return 0;
}
So if we start from the top there is a problem in the calculateRand() function as you do not declare the UPPER and LOWER variables or pass them as parameters to function.
Swap function is ok.
In the BubbleSort() function you need to decrease the up variable value after the for loop.
while(up>1)
{
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
up--;
}
Also at this point you should start iterating from 0 instead of 1 since arrays start from index 0. So for(i=0; i<up-1; i++) is the correct way to go.
Lastly in the main() function when you're declaring the array variable S you shouldn't pass the sizeof(n) since n is an integer and size of an integer is 4. Instead you want to use n as it is int S[n];
For loop to populate the array should go up to n not n-1 if you want to fill all elements of the array. However if you change this you'll need to make the similar change in the BubbleSort() function.
And finally in the BubbleSort() function call you are passing the last element of the array which is an integer whereas function expects you to pass an array. It should look like this BubbleSort(S, n); instead.
sizeof(n) has nothing to do with the value of the variable n. It's the the size of the variable n, i.e. mostly 4 bytes for the modern architectures.
Modern variants of C permit variable size arrays thus
int S[n];
would have been legit. Otherwise
int *S = (int *)malloc(n*sizeof(int));
will help.
When you call BubbleSort , your argument should be S not S[sizeof(n)];

Creating a function for a random number 2D array

So, I have this code which I need to turn into a function:
int main(void) {
int i=0,seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
printf("\nSeed value is:%d\n\n",seed);
srand(seed);
int a[5][5];
int x,y;
printf("Matrix A:\n");
for(x=0;x<5;x++) {
for(y=0;y<5;y++) {
a[x][y] = rand() %51 + (-25);
printf("%d ",a[x][y]); }
printf("\n"); }
printf("\n\n");
So basically, it produces a 2D 5x5 array of random numbers. This works fine, however my next task is applying a function to this code, with the function name of:
void generate_matrices(int a[5][5])
I have tried multiple times, the closest I got to a successful code was:
#include <stdio.h>
#include <stdlib.h>
void generate_matrices(int a[5][5]);
int main(void) {
int a, seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
srand(seed);
printf("\nSeed value is:%d\n\n",seed);
generate_matrices(a);
return 0;
}
void generate_matrices(int a[5][5]) {
int y,z;
printf("Matrix A:\n");
for(y=0;y<5;y++) {
for(z=0;z<5;z++) {
a[y][z] = rand() %51 + (-25); }
printf("%d ",a[y][z]); }
printf("\n");
}
But this returns the error, "expected 'int(*)[5]' but arguement is of type 'int'.
All/any help is muchly appreciated. To be fair on my part, I have done 90% of the code. This is the only bit I need help with so that I can apply this to the rest of my code.
Cheers!
You have declared a as a single integer on this line int a, seed;
When you call the function with generate_matrices(a); you are passing a single integer instead of a pointer to an array.
Change your declaration line to int a[5][5], seed;
generate_matrices(a); will pass a pointer to the first element in your 5 * 5 array, to the function.
You should really print the results in main and not in the function, then you will know that the array has been modified and is available for use in the body of your program.
You have used unconventional placement of braces '}' and this makes it harder to see what belongs in each part of your for loops.
You have the print statements in the wrong places - as a result only part of the matrix is printed.
This is what it should be (just the results - in main):
printf("Matrix\n ");
for (y = 0; y < 5; y++) {
for (z = 0; z < 5; z++) {
printf("%d\t ", a[y][z]);
}
printf("\n");
}
If you use int a[5][5] and call the function with generate_matrices(a);
a function void generate_matrices(int a[5][5]) {...} compiles without error
#include<stdio.h>
#include<stdlib.h>
void modify(int b[5][5]);
int main()
{
srand(4562);
int i,j,arr[5][5];
modify(arr);
for(i=0;i<5;i++){
for(j=0;j<5;j++){
printf("%d ",arr[i][j]=rand() %51 + (-26)); }
}
return 0;
}
void modify(int b[5][5])
{
int i,j;
for(i=0;i<5;i++) {
for(j=0;j<5;j++) {
b[i][j]; }
}
}
So this is the closest I have come to completing it. It produces the number of elements I want, also within the range I want. However its not producing the 5x5 grid I need. Where have I gone wrong?
EDIT: I'm not going for neatness at the moment, I just want to get the program working how I want it too and then i'll neaten it up.
EDIT 2: Never mind, realised what I didn't include. Its fine now. Thanks for the help.

C: format '%s' expects argument of type 'char*', but argument 2 has type 'char**'

I try to type simple 2D array of string take strings from user and print it
void in(char* n[3][2]);
void show_name ()
{
char* n[3][2];
in(n);
unsigned int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf("%s ", &n[i][j]);
printf("\n");
}
}
int main(void)
{
show_name();
return 0;
}
void in(char* n[3][2])
{
int i,j;
for(i=0;i<3;i++)
for(j=0;j<2;j++)
scanf("%s",&n[i][j]);
printf("\n");
}
it works correctly but i have warning say:
warning: format '%s' expects argument of type 'char*', but argument 2
has type 'char**' [-Wformat]|
I searched for reason i found that the problem in %s doesn't need for address
when i remove & operator there`s no warning but code doesn't run correctly
I have simplified and corrected your program, commenting where I changed it.
EDIT how to make it easy to change the number of strings, now 6 as above comments
#include <stdio.h>
#define STRINGS 6
void in(char n[][200]); // no need for * and array
void show_name ()
{
char n[STRINGS][200] = {}; // allow some string space and init for security
int i;
in(n);
for(i=0; i<STRINGS; i++) // only need to iterate one dimension
printf("%s\n", n[i]);
}
int main(void)
{
show_name();
return 0;
}
void in(char n[][200]) // needs length of each row, but not number of rows
{
int i;
for(i=0; i<STRINGS; i++) // only need to iterate one dimension
scanf("%199s", n[i]); // restrict the input length
printf("\n");
}

How to pass in function a multidimensional char array in C?

This is my code and it is not working.
It generate these errors when I pass char array like this grid[r][c]
[Error] use of parameter 'r' outside function body
[Error] use of parameter 'c' outside function body
It generate these errors when I pass char array like this grid[][c]
[Error] use of parameter 'c' outside function body
It generate these errors when I pass char array like this grid[][]
[Error] declaration of 'grid' as multidimensional array must have bounds for all dimensions except the first
And it runs perfectly fine when I pass this like this grid[1][2] i.e. just passing with an integer.0
I am stuck here and I don't know what to do or what not??
How to get rid of this problem?? Help Me !!!
Thanks in Advance!
void dfs(int r, int c, int pacman_r, int pacman_c, int food_r, int food_c, char grid[r][c]) {
//logic here
}
int main(void) {
int r, c;
int pacman_r, pacman_c;
int food_r, food_c;
scanf( "%d %d", &pacman_r, &pacman_c);
scanf( "%d %d", &food_r, &food_c);
scanf( "%d %d", &r, &c);
char grid[r][c];
for( int i=0; i<r; i++) {
scanf("%s[^\\n]%*c", grid[i]);
}
dfs( r, c, pacman_r, pacman_c, food_r, food_c, grid);
return 0;
}
you should pass the argument as a char* then work with it as a pointer to a flattened instance of your array
void fn(char* grid, int c){
printf("%c", (grid+n*c)[m]);
}
this will print `grid[n][m]

Resources