Alright so I'm sure this is pretty simple and all but I have no idea how to use functions. Up until now I was able to get by with everything in main but now I'm required to use functions for just about anything I do. So from my code below, how do I read in (or w.e. the proper terminology is) a function from main?
EDIT: To clarify to everyone, my question is how can I access the array I returned in main?
Code below takes in the test scores from different amount of students specified by user input.
#include <stdio.h>
#include <stdlib.h>
int** getTestData();
int main (){
///this is where I'm lost..
int (*a)[];
a = getTestData();
}
int** getTestData(){
int students, numberOfTests, testScores, i, j;
int** testScoreBank;
// reads in studens
scanf("%i", &students);
testScoreBank = (int**) malloc (sizeof(int)*students);
for(i=0; i<students;i++){
//how many number of tests there are
scanf("%i", &numberOfTests);
testScoreBank = (int*) malloc (sizeof(int)*numberOfTests);
for(j=0; j<numberOfTests; j++){
//the tests themselves
scanf("%i", &testScores);
testScoreBank[i][j] = testScores;
}
}
return testScoreBank;
}
Ok, here is an example with global variables, how to fill your array inside a function, and access it in main()
#include <stdio.h>
#include <stdlib.h>
int** getTestData();
int numberOfStudents;
int* studentTestSizes;
int main (){
int** testScoresBank = getTestData();
int i, j;
for (i = 0; i < numberOfStudents; i++) {
for (j = 0; j < studentTestSizes[i]; j++) {
printf("%d", testScoresBank[i][j]);
}
}
return 0;
}
int** getTestData() {
int** testScoreBank;
// reads in studens
scanf("%d", &numberOfStudents);
testScoreBank = malloc(sizeof(int*) * numberOfStudents);
studentTestSizes = malloc(sizeof(int) * numberOfStudents);
int i;
for (i = 0; i < numberOfStudents; i++) {
//how many number of tests there are
scanf("%d", studentTestSizes + i);
testScoreBank[i] = malloc(sizeof(int) * studentTestSizes[i]);
int j;
for (j = 0; j < studentTestSizes[i]; j++) {
//the tests themselves
int testScore;
scanf("%d", &testScore);
testScoreBank[i][j] = testScore;
}
}
return testScoreBank;
}
alternative for global variables is to make global variables local and pass pointers to them to getTestData function, example is here:
#include <stdio.h>
#include <stdlib.h>
int** getTestData();
int main (){
int numberOfStudents; // those variables are now here
int* studentTestSizes;
int** testScoresBank = getTestData(&numberOfStudents, &studentTestSizes); // passing the pointers so we can change values that are pointed to
int i, j;
for (i = 0; i < numberOfStudents; i++) {
for (j = 0; j < studentTestSizes[i]; j++) {
printf("%d", testScoresBank[i][j]);
}
}
return 0;
}
int** getTestData(int* numberOfStudentsPtr, int** studentTestSizesPtr) {
int** testScoreBank;
// reads in studens
scanf("%d", numberOfStudentsPtr); // it's already a pointer so we must omit &
int numberOfStudents = *numberOfStudentsPtr; // will be constant from now on
testScoreBank = malloc(sizeof(int*) * numberOfStudents);
*studentTestSizesPtr = malloc(sizeof(int) * numberOfStudents);
int* studentTestSizes = *studentTestSizesPtr;
int i;
for (i = 0; i < numberOfStudents; i++) {
//how many number of tests there are
scanf("%d", studentTestSizes + i);
testScoreBank[i] = malloc(sizeof(int) * studentTestSizes[i]);
int j;
for (j = 0; j < studentTestSizes[i]; j++) {
//the tests themselves
int testScore;
scanf("%d", &testScore);
testScoreBank[i][j] = testScore;
}
}
return testScoreBank;
}
In addition to the other answers, you have a number of subtle issues to consider. Two are just general helpful tips for writing/debugging your beginning applications (1) if you are taking user input, prompt for it - you can strip the prompts later, but it is much easier to enter data in response to an informative prompt than it is to wonder what the blinking cursor is doing down there -- did to program freeze?; (2) provide adequate spacing in your code - you can always delete blank lines later, but separating your code into functional blocks of logic will help you keep your logic straight.
When allocating space for numeric arrays, it is good practice to initialize all values to 0 as part of (or after) allocation. This will absolutely prevent the inadvertent read from uninitialized space. You can allocate and initialize all at once by using calloc instead of malloc. This also provides benefits when allocating arrays of pointers to char* as well.
While you may have fixed your allocation, you still have the glaring problem of knowing "How many students and tests do I have?". Here is where passing an additional pointer for the number of students and storing the number of tests in an additional array index is required. (there are other ways to do it, this is just efficient). You can declare the the number of students in main passing its pointer to getTestData. Updates to the value of students in getTestData are then available in main. But, "What if the students have a different number of scores? What then?" You are already filling an array of integers, if you just store the number of tests for the student as the first integer, you make that value available no matter where you pass the array.
Finally, you need to pay closer attention to your choice of variable types. For indexes and lengths that can never be negative, unsigned or size_t is a better choice and will allow the compiler to point out instances where you may be using that value incorrectly.
You need to validate each time you allocate memory with malloc or calloc, and you are responsible to keeping track of the address to the start of each allocation and freeing it when it is no longer needed.
That said, here is one approach to making it all work. Try it. Let me know if you have any questions:
#include <stdio.h>
#include <stdlib.h>
int **getTestData (size_t *students);
int main (void) {
int **a = NULL;
int j;
size_t i, s = 0;
if (!(a = getTestData (&s))) {
fprintf (stderr, "error: getTestData failed to return student data.\n");
return 1;
}
/* print student data */
putchar ('\n');
for (i = 0; i < s; i++)
{
printf (" Student[%2zu] scores : ", i+1);
/* adjust indexes to read no. of tests */
for (j = 1; j < a[i][0]; j++)
printf (" %3d", a[i][j]);
putchar ('\n');
}
putchar ('\n');
/* free allocated memory */
for (i = 0; i < s; i++)
free (a[i]);
free (a);
return 0;
}
int **getTestData (size_t *students)
{
size_t tests, testScores, s, t;
int **testScoreBank;
/* reads in students */
printf ("\n No. of students: ");
scanf ("%zu", students);
if (!(testScoreBank = calloc (*students, sizeof *testScoreBank))) {
fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
return NULL;
}
for (s = 0; s < *students; s++)
{
/* how many number of tests there are */
printf ("\n No. of scores for student[%2zu]: ", s+1);
scanf ("%zu", &tests);
tests += 1; /* allow space for number of tests as [s][0] */
testScoreBank[s] = calloc (tests, sizeof **testScoreBank);
testScoreBank[s][0] = tests;
for (t = 1; t < tests; t++)
{
/* the tests themselves */
printf (" student[%2zu]-test[%2zu] score: ", s+1, t);
scanf ("%zu", &testScores);
testScoreBank[s][t] = testScores;
}
}
return testScoreBank;
}
Use/Output
$ ./bin/testdata
No. of students: 2
No. of scores for student[ 1]: 3
student[ 1]-test[ 1] score: 88
student[ 1]-test[ 2] score: 91
student[ 1]-test[ 3] score: 82
No. of scores for student[ 2]: 4
student[ 2]-test[ 1] score: 93
student[ 2]-test[ 2] score: 95
student[ 2]-test[ 3] score: 96
student[ 2]-test[ 4] score: 91
Student[ 1] scores : 88 91 82
Student[ 2] scores : 93 95 96 91
(I assume this is just a snippet of your overall code and there's more to it or else you might have other problems)
Anyway you should be able to set up your 2D array with the following modifications:
scanf("%i", &students);
testScoreBank = malloc (sizeof(int*)*students); //sizeof int* instead of sizeof int.
for(i=0; i<students;i++)
{
scanf("%i", &numberOfTests);
*(testScoreBank + i)= malloc (sizeof(int)*numberOfTests); //You forgot the * operator on testScoreBank and to iterate through it.
for(j=0; j<numberOfTests; j++)
{
scanf("%i", &testScores);
testScoreBank[i][j] = testScores;
}
}
Related
I am trying to sort an array of structs (A SJF Scheduler). I am using the qsort library function to sort the structs in increasing order according to the attribute bursttime. However, the output is not correct. I've checked some SO questions about the same but they served no use.
struct job
{
int jobno;
int bursttime;
};
typedef struct job job_t;
int mycompare(const void* first, const void* second)
{
int fb = ((job_t*)first)->bursttime;
int sb = ((job_t*)second)->bursttime;
return (fb - sb);
}
int main()
{
int n;
printf("Enter number of jobs: ");
scanf("%d", &n);
job_t* arr = (job_t*)malloc(sizeof(job_t) * n);
for(int i = 1; i <= n; ++i)
{
printf("Enter Burst time for Job#%d: ",i);
scanf("%d", &(arr[i].bursttime));
arr[i].jobno = i;
}
printf("\n");
printf("Order of the Jobs before sort:\n");
for(int i = 1; i <= n; ++i)
{
printf("%d\t", arr[i].jobno);
}
qsort(arr, n, sizeof(job_t), mycompare);
printf("\n");
printf("Order of the Jobs after sort:\n");
for(int i = 1; i <= n; ++i)
{
printf("%d\t", arr[i].jobno);
}
printf("\n");
printf("\n");
return 0;
}
This is my inputfile:
4
7
2
9
4
The output I'm getting is:
Order of the Jobs before sort:
1 2 3 4
Order of the Jobs after sort:
2 1 3 4
The expected order should be: 2,4,1,3. Am I missing anything?
At least this problem
for(int i = 1; i <= n; ++i) // bad
Use zero base indexing.
for(int i = 0; i < n; ++i)
You could change the indexing scheme to start from zero, as others have suggested, and this would certainly be the idiomatic way to do it.
But if you want to use 1-based indexing, you'll need to allocate an extra place in the array (position 0 that will never be used):
job_t* arr = (job_t*)malloc(sizeof(job_t) * (n + 1));
Then you'll need to start your sort at position 1 in the array:
qsort(&arr[1], n, sizeof(job_t), mycompare);
And, of course, you'll have to write your code to index from 1 -- but you've already done that.
The problem is that so many standard functions in C use zero-based indexing that doing anything else is inexpressive. That's a bigger problem than wasting one array position. But, for better or worse, I've had to convert to C a load of code from Fortran, so I've gotten used to working both ways.
I am attempting to create a dynamic array that will grow in size if needed, as I don't know how large the array will actually be. My code seems to work until the 8th element of the array where I start to see very large incorrect values that I did not enter. Not sure why this is happening.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv)
{
int val;
int userInput;
int* arr;
int size = 1;
int arrIndex = 0;
arr = (int*) malloc(sizeof(int) * size);
/* prompt the user for input */
printf ("Enter in a list of numbers to be stored in a dynamic array.\n");
printf ("End the list with the terminal value of -999\n");
/* loop until the user enters -999 */
scanf ("%d", &val);
while (val != -999)
{
if (arrIndex >= size)
{
size++;
}
arr[arrIndex] = val;
arrIndex++;
/* get next value */
scanf("%d", &val);
}
int j = 0;
for(j = 0; j < size ; j++)
{
printf("%d \t", arr[j]);
}
}
The size of the array remains 1 and doesn't increase while incrementing size variable.
Your code worked until 8th element because adjacent memory after the array upto 7th element must be free.
In C array index out of bound is not checked and it is programmers responibility.
if you want to increase or decrease size of array you can use realloc inside while loop:
arr=(int*)realloc(arr,sizeof(int)*size);
Also Correct this if condition in your code initially arrayindex is 0 and size is 1 which results in false.
if (arrIndex >= size)
{
size++;
}
I've been trying to build a recursive function which calculates the max value, but even I can see the total value when I print in the function, I can't return the value to the main function. Can you tell me where do I do wrong? Thanks for help!
note : more explanation about what I ve been trying to build is : user defines an object and as long as user doesn't give the price, I keep asking what the object is..
small example :
Define the object:
Car
What is Car?:
4*Wheel+1*Frame
What is Wheel?:
2*Rim
What is Rim?
5.0
What is Frame?:
10.0
Total is : 50.0
Current code:
#include <stdio.h>
#include <stdlib.h>
#define INPUT_SIZE 101
void delete_space(char arr[])
{
int a, i, j, len;
for(a = 0; a < INPUT_SIZE; a++)
{
for(i = 0; i < INPUT_SIZE; i++)
{
if(arr[i] == ' ')
{
for(j = i; j < INPUT_SIZE; j++)
{
arr[j] = arr[j + 1];
}
}
}
}
}
double result(char input[], double coeff, double total)
{
/* if the input is number, num_of_obj is 0, if the input is object, num_or_obj is more than 0.
*/
int i, k = 1, num_of_obj = 0;
char temp_input[INPUT_SIZE];
char temp_input_1[INPUT_SIZE];
char x;
int* p;
double value;
p = (int*)calloc(1, sizeof(int));
p[0] = 0;
printf("What is %s:?\n", input);
scanf("%[^\n]s", temp_input);
getchar();
delete_space(temp_input);
for(i = 0; i < INPUT_SIZE; i++)
{
if(temp_input[i] == '*')
{
num_of_obj++;
}
}
if(num_of_obj == 0) // if the input is number.
{
sscanf(temp_input, "%lf", &value);
total = total + coeff * value;
printf("total : %lf", total);
return total;
}
if(num_of_obj > 0)
{
for(i = 0; i < INPUT_SIZE; i++)
{
if(temp_input[i] == '+')
{
p = (int*)realloc(p, (k + 1) * sizeof(int));
p[k] = i + 1;
k++;
}
}
for(i = 0; i < k; i++)
{
sscanf(&temp_input[p[i]], "%lf%c%[^+]s", &coeff, &x, temp_input_1);
result(temp_input_1, coeff, total);
}
}
printf("test");
return total;
}
int main()
{
double total = 0;
char input[INPUT_SIZE];
printf("Define the object :\n");
scanf("%[^\n]s", input);
getchar();
delete_space(input);
printf("total : %.2lf", result(input, 0, 0));
return 0;
}
I believe that the main issue is the recursive call: result(temp_input_1, coeff, total);, which is ignoring the returned result.
Two possible solutions: (1) do the aggregation in result OR (2) tail recursion. I'm not sure that this case fit into tail recursion (or that there are any benefits here). Consider removing the 'total' from result prototype, and doing the aggregation (over the 'components') in the loop.
double result(char input[], double coeff) {
double total ;
...
for(i = 0; i < k; i++)
{
sscanf(&temp_input[p[i]], "%lf%c%[^+]s", &coeff, &x, temp_input_1);
total += result(temp_input_1, coeff, total);
}
Side comment: Consider also removing the 'delete_space' function. I believe it does not property fix the string. Much easier to skip over the spaces in the scanf call.
Welcome to stackoverflow! I too am new here, but if you word your questions right, you'll get better answers. If this is a homework assignment, I highly recommend including that, it can be hard to follow descriptions.
So as a general rule of thumb, when writing C functions its best to use as few return statements as possible. But I too have difficulty with this.
It looks like your are checking for
is first condition met?
if not check next condition
should you be using if, if else, and else?
Also you have if statements with no else, generally needed, especially in a recursive function (you might be skipping over the next step after the last recursive call)
Hope this helps! Swamped with the end of the semester myself or else I would have attempted a solution!
You need three things to write a recursive method successfully:
A terminating condition, so that the method doesn't call itself forever,
Some work to do, and
A recursive call.
Consider the following code:
typedef struct node{
void* item;
struct node* next;
} Node;
int CountNodes(Node* list)
{
if (list == null) return 0;
return 1 + CountNodes(list.next);
}
This code works because it counts the current node plus all remaining nodes. The recursive call counts the next node and all remaining nodes. And so on.
Define a struct named Book. Each book should have a name with
exactly 3 letters (abbreviation). Each book should also have a page
count (integer), and a price (integer).
Write a program which reads an integer n first, then reads the
names, page counts and prices of n books.
Write a function which takes an array of books, and sorts them
according to their prices. Using that function, your program should
print the names and page counts of each book with the order of their
prices.
My Question
Can someone explain to me how to pass a structure into a function and get this code to work? Or how they would go tackle this question.
struct Book{
char name[3];
int pagec;
int price;
};
void price(int size, struct Book books[size]){
int i,j, tmp;
for(i=0; i<size; i++){
for(j=0; j<size-1; j++){
if(books[j].price < books[j+1].price){
books[j].price = tmp;
books[j].price = books.price[j+1];
books.price[j+1] = tmp;
}
}
}
}
int main(void) {
int n;
scanf("%d", &n);
struct Book books[n];
int i,j;
for(i=0; i<n; i++){
for(j=0; i<1; j++){
scanf("%c", &books[i].name);
scanf("%d", &books[i].pagec);
scanf("%d", &books[i].price);
}
}
price(n, books[n]);
for(i=0; i<n; i++){
printf("%c: %d - %d",books[i].name, books[i].pagec, books[i].price);
}
The part of your question about how to pass a struct seems to have been well answered, let me get on the second part: how I would tackle that question.
What the struct should be is described well, so we can write without much thinking:
/*
Define a struct named: Book.
Each book should have a name with exactly 3 letters (abbreviation).
Each book should also have a page count (integer),
and a price (integer).
*/
typedef struct book {
// three characters plus '\0'
char name[4];
int pagec;
int price;
} book_t;
(No need for a typedef you can leave that part out and use the struct directly with struct books)
They want three functions, one is main() we can use it as one of the three. I think getting the info, allocating the memory etc. is a good use of the main() function here.
/*
Write a program which
reads an integer n first,
then reads the names,
page counts
and prices of n books.
*/
int main()
{
int n, i;
book_t **books;
puts("How many books?");
scanf("%d", &n);
// we need enough memory to safe "n" structs
// at first allocate memory for n pointers
books = malloc(n * sizeof(book_t *));
// at each pointer allocate enough memory for one struct books
for (i = 0; i < n; i++) {
books[i] = malloc(sizeof(book_t));
}
// red the info from stdin
for (i = 0; i < n; i++) {
printf("Name of book (3 letter abbrev.):");
scanf("%3s", books[i]->name);
printf("Number of pages:");
scanf("%d", &books[i]->pagec);
printf("Price of book (incl. taxes):");
scanf("%d", &books[i]->price);
}
// call function to sort them
sort_books(books, n);
// call a function to print the sorted list
print_books(books, n);
// we don't need the memory anymore, so free it
// at first free the individual structs
for (i = 0; i < n; i++) {
free(books[i]);
}
// then free the memory holding all of the pointers
free(books);
exit(EXIT_SUCCESS);
}
The two functions for printing and sorting are similar in argument handling
/*
Write a function which takes an array of books,
and sorts them according to their prices.
Doesn't say something about output, so sort in situ
*/
void sort_books(book_t ** books, int length)
{
// OP had bubble sort, so lets do a bubble sort. Why not?
int i, j;
book_t *tmp;
for (i = 0; i < length - 1; i++) {
for (j = 0; j < length -i - 1; j++) {
if (books[j]->price < books[j + 1]->price) {
tmp = books[j];
books[j] = books[j + 1];
books[j + 1] = tmp;
}
}
}
}
Printing them all is quite straightforward
/*
Using that function, your program should
print the names and page counts of each book with the order of their prices.
*/
void print_books(book_t ** books, int length)
{
int i;
for (i = 0; i < length; i++) {
printf("Name %s, pages %d, price %d\n",
books[i]->name, books[i]->pagec, books[i]->price);
}
}
It doesn't say anything about the exact order, I took the liberty to use a descending order (from highest to lowest). If you want an ascending order (from lowest to highest) change the comparing in the sorting algorithm:
void sort_books(book_t ** books, int length)
{
// OP had bubble sort, so lets do a bubble sort
int i, j;
book_t *tmp;
for (i = 0; i < length - 1; i++) {
for (j = 0; j < length - i - 1; j++) {
// if (books[j]->price < books[j + 1]->price) {
if (books[j]->price > books[j + 1]->price) {
tmp = books[j];
books[j] = books[j + 1];
books[j + 1] = tmp;
}
}
}
}
Please be aware that I omitted all checks! You need to check the returns of malloc() and scanf(), if n is an integer, if all of the other numbers are numbers and so on!
books[n] is one struct Book (or would be, if the array had n+1 elements).
The name of the array is just books, and this is what you should pass to the function:
price(n, books);
So you have your struct
struct Book{
char name[10];
int pagec;
int price;
};
You can pass it in by passing in a pointer to it using the "address of" operator
void receivingFunction(Book* myBook)
{
printf("%s", myBook->name);
}
void sendingFunction()
{
Book myBook;
//set values in myBook
receivingFunction(&myBook);
}
Notice that when you are working with the pointer to book, you access members using the -> operator, not the . operator.
Now that example above is just for passing in a single instance. What if you want to pass in an array? It'll look something like this.
#include <stdio.h>
#include <string.h>
struct Book{
char name[4]; //other answers explain well why I changed this to 4
int pagec;
int price;
};
void BookSorter(struct Book books[10], int booksLength)
{
int i;
for(i = 0; i < booksLength; i++)
{
printf("%s %d %d\n", books[i].name, books[i].pagec, books[i].price);
}
}
int main(void)
{
Book books[10];
//define your values for books here
//mine are junk values since this is just an example
for(int i = 0; i < 10; i++)
{
strncpy(books[i].name, "aaa", 4);
books[i].pagec = 4;
books[i].price = 10;
}
//
BookSorter(books, 10);
}
From here you can modify your bubble sort to iterate through your array instances and swap them. I'm not going to include that part because 1) it is beyond the scope of your original question about passing structs and 2) it really looks like you're doing homework and I don't want to give you all of it. The comments below your question address ways to fix your bubble sort, one I haven't seen yet is that you're just swapping the prices of the books, not the books themselves. Your temp variable should be a struct Book, not an int. Your swapping just swaps the prices of the books, which will lead to them being assigned to the wrong book for the final printing out of the answer, with the books and page counts being left in the same order they were read in. It looks like you used this example code (or maybe one of a million like it), but here it is if you need a reference for implementing bubble sort.
Given this task:
Write a program that allocates the necessary amount of memory for storing the elements from two [m x n] integer matrices.
I don't know how to allocate memory to 2 Dimensional arrays.
I read some examples but I don't get it.
#define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#define DIM 10
void main()
{
int **m, *n;
int i = 0, j = 0;
int diml, dimc;;
puts("Introduceti dimensiunea matricelor(linii|coloane)");
scanf("%d%d", &diml, &dimc);
m = (int**)malloc(dimc*sizeof(int));
puts("Introduceti elementele primei matrici:");
for (j = 0;j < dimc;j++)
{
m[i] = (int *)malloc(diml*(sizeof(int)));
}
for (j = 0;j < dimc;j++)
{
for (i = 0;i < diml;i++)
{
printf("tab[%d][%d]= ", j + 1, i + 1);
scanf("%*d", m[j][i]);
}
}
_getch();
}
My program crash after I enter the first line.
Introduceti dimensiunea matricelor(linhi I coloane)
3
3
Introduceti elementele primei matrici:
ab[1][1]= 2
ab[1][2]= 1
ab[1][3]= 2
ab[2][1]=
Problema 3.exe has stopped working
A problem caused the program to stop working correctly.
Windows will closethe program and notify you if a solution is
available.
Avoid the mistake of allocating using the wrong size by allocating based on the size of the object and not the size of type. If the sizeof(int) was less then sizeof(int *), this would explain OP's problem.
// m = (int**)malloc(dimc*sizeof(int)); // Original
// m = (int**)malloc(dimc*sizeof(int *)); // corrected type
// m = malloc(dimc*sizeof(int *)); // cast not needed
m = malloc(sizeof *m * dimc); // best : sizeof object
Use correct index j vs. i #BLUEPIXY. This is certainly an issue for OP.
for (j = 0;j < dimc;j++) {
// m[i] = (int *)malloc(diml*(sizeof(int)));
m[j] = malloc(sizeof *(m[j]) * diml);
Insure compiler warnings are fully enabled - it should have caught this one.
// scanf("%*d", m[j][i]);
scanf("%d", &m[j][i]);
Suggest checking the results of malloc() and scanf().
#include <stdlib.h>
m[j] = malloc(sizeof *(m[j]) * diml);
if (m[j] == NULL && diml != 0)) {
fprintf(stderr", "Out of memory\n");
return EXIT_FAILURE;
}
if (scanf("%d", &m[j][i]) != 1) {
fprintf(stderr", "Non-numeric input\n");
return EXIT_FAILURE;
}
main() should return int.
#include <stdlib.h>
int main(void) {
...
return EXIT_SUCCESS;
}
When promoting, insure output gets printed and is not buffered. Use fflush() or end the prompt with '\n'.
printf("tab[%d][%d]= ", j + 1, i + 1);
fflush(stdout); // add
scanf(...
You should allocate like this at first:
m = (int**)malloc(dimc*sizeof(int*));
After that you allocate like that:
m[i] = (int *)malloc(sizeof(int));