funny characters output for a sum function (Φw ÅΩw) [duplicate] - c

This question already has answers here:
printf() no format string printing character and integer arrays --> garbage
(3 answers)
Closed 2 years ago.
I am having a crazy output with funny characters (Φw    ÅΩw) can i know what's wrong in the code?
probably the int main is wrong
i am obliged with int sumArray (int * a, int len , int * sum )format
#include <stdio.h>
#include <stdlib.h>
int sumArray(int *a, int len, int *sum) {
int sum1 = 0;
if (a == NULL || sum == NULL)
return -1;
int i;
(*sum) = 0;
for (i = 0; i < len; i++) {
(*sum) += a[i];
}
return 0;
}
int main() {
int *a = {1, 2, 3, 4};
int *b;
sumArray(&a, 4, &b);
printf(b);
return 0;
}

Can you try these changes ?
#include <stdio.h>
#include <stdlib.h>
int sumArray(int *a, int len, int *sum) {
// int sum1 = 0; // i removed this variable because you are not using it
if (a == NULL || sum == NULL)
return -1;
int i;
(*sum) = 0;
for (i = 0; i < len; i++) {
(*sum) += a[i];
}
return 0;
}
int main() {
// int *a = {1, 2, 3, 4};
int a[] = {1, 2, 3, 4};
int b;
// i rather declare an integer instead of a pointer to an integer
// when you declared int * b , this was a pointer, and your printf(b) was
// printing an address, not the value calculated by sumArray that is why you
// were printing funny characters
sumArray(a, 4, &b);
// a is already a pointer
printf("%d", b);
return 0;
}

You are using your pointers uninitialized. When you create a pointer, you don't know where the pointer points to. It either will be pointing to some garbage data, or in worse case, it will be pointing to a memory region which is already being used by some other program in your computer or maybe by OS itself.
If you really want to use pointers like this, you should dynamically allocate memory for them.
int* a = malloc( 4 * sizeof(int) );
int* b = malloc( sizeof(int) );
This makes sure that you can assign four integers to the memory region to which a points to. And one for b.
You then can wander in that memory using loops to assign, read or write data.
for ( int i=0; i < 4; i++ )
{
*(a + i) = i + 1;
}
Here we have a for loop which will run 4 times. Each time we are moving one block in the memory and putting the number we want there.
Remember, a is a pointer, it points to the beginning of a 4 int sized memory region. So in order to get to the next block, we are offsetting our scope with i. Each time the loop runs, a + i points to the "ith element of an array". We are dereferencing that region and assigning the value we want there.
for ( int i=0; i < 4; i++ )
{
printf("%d\n", *(a + i) );
}
And here we are using the same logic but to read data we just write.
Remember, you need to use format specifiers with printf function in order to make it work properly. printf() just reads the whatever data you happened to give it, and format specifier helps interpret that data in given format.
If you have a variable like int c = 65; when you use %d format specifier in the printf you will read the number 65. If you have %c specifier in the printf, you will read letter A, whose ASCII code happens to be 65. The data is the same, but you interpret it differently with format specifiers.
Now, your function int sumArray(int *a, int len, int *sum) accepts int pointer for the first argument. In the main function you do have an int pointer named a. But you are passing the address of a, which results in double indirection, you are passing the address of a pointer which holds address of an int array. This is not what you want, so & operator in the function call is excess. Same with b.
Call to the sumArray should look like
sumArray( a, 4, b );
And lastly, we should fix printf as well. Remember what I said about format specifiers.
And remember that b is not an int, it's int*, so if you want to get the value which b points to, you need to dereference it.
In the end, call to printf should look like
printf( "%d", *b );
Also, you should remember to free the memory that you dynamically allocated with malloc. When you use regular arrays or variables, your compiler deals with these stuff itself. But if you dynamically allocate memory, you must deallocate that memory using free whenever you are done with those pointers.
You can free a after the call to sumArray and b before terminating the main function like
free(a); and free(b);
In these kind of small projects freeing memory is probably won't cause any unwanted results, but this is a very very important subject about pointers and should be implemented properly in order to settle the better understanding of pointers and better programming practice.
In that form, your code should work as you intended.
BUT... And this is a big but
As you can see, to make such a simple task, we spent way more effort than optimal. Unless your goal is learning pointers, there is no reason to use pointers and dynamic allocation here. You could have used regular arrays as #Hayfa demonstrated above, and free yourself from a lot of trouble.
Using pointers and dynamic memory is a powerful tool, but it comes with dangers. You are playing with actual physical memory of your computer. Compilers nowadays won't let you to screw your OS while you are trying to add two numbers together but it still can result in hard to detect crashes especially in complex programs.
(Sorry if it's hard to read, I am not necessarily confident with text editor of Stack Overflow.)

Related

Reason for Segmentation fault vs returning random values with the following C code

Please explain (reason for the output) what happens as a result of running the two segments of code. Please explain their difference too. There are two versions of setArr(int, int) as explained below...
#include <stdio.h>
void setArr(int, int);
int *arr[10]; // array of 10 int pointers
int main(int argc, char *argv[]) {
int i;
setArr(0, 0);
setArr(1, 100);
setArr(2, 200);
setArr(3, 300);
setArr(4, 400);
for (i = 0; i < 5; i++)
printf("arr[%d]: %d\n", i, *arr[i]); /* should be 0,100, 200,300,400 */
return 0;
}
Versions of setArr
Version A
void setArr(int index, int v) {
int i = v;
*arr[index] = i;
}
Output: Segmentation fault (core dumped)
Version B
void setArr(int index, int v) {
int i = v;
arr[index] = &i;
}
Output:
arr[0]: 400
arr[1]: 32748
arr[2]: 32748
arr[3]: 32748
arr[4]: 32748
I presume the values from running Version B are just random values.
I am fairly new to pointers I have knowledge in Java, so please explain it as beginner friendly as you can :)
You are hitting a lot of undefined behavior scenarios, but I will explain what is likely happening.
arr is an array of 10 pointers to integers.
int * arr[10]; // array of 10 int pointers
And when declared as a global variable, all of those pointers are going to be zero-initialized - so hence, it's an array of 10 NULL pointers.
So this line in version A, is dereferencing the address at arr[index]:
* arr[index] = i;
Is effectively saying this:
*(NULL) = i;
And that will certainly crash consistently.
In Version B, you have it as:
int i = v;
arr[index] = &i;
So now you are correctly assigning a pointer to a slot in the array. However that address getting assigned is to a local stack variable, i, which goes out of scope as soon as the function returns. So when you print the value at that address, it's most certainly been clobbered from other calls writing on top of the stack. (Or technically this "undefined behavior" of accessing a memory address of a stack variable that has gone out of scope.)
Better:
void setArr (int index, int v){
arr[index] = malloc(sizeof(int));
*arr[index] = v;
}
The above allocates memory for the address that you want to copy that value into. You're on your own for how to free that memory.
Alternatively:
Just declare arr as an array of integers instead of pointers:
int arr[10];
void setArr (int index, int v){
arr[index] = v;
}
And then print normally without the * deference thing on arr.
printf("arr[%d]: %d\n", i, arr[i]);
Version A says "the contents of an undefined pointer equals i" - undefined behavior = crash. Basically you are trying to write to some unknown location in memory.
Version B says "Some pointer = some address" - still undefined behavior as &i goes out of scope, but it is still an address and so it "kind of works". Here you are writing to "good" memory locations, but reading from bad ones.
in first case, you have defined the "array of pointers" to integer. They are not integer pointers. Either you will have to allocate memory (preferably using melloc/calloc functions) before storing any value to them OR you can define the array of integer like this:
int (*a)[10]
The following link may show you some idea about it: Difference between *ptr[10] and (*ptr)[10]
In second case, you are saving the address of integer into integer pointer, which is ok, but int i is local variable to function setArr(). This will therefore, the value of int i will be dereferenced every time the function setArr() exits. Therefore you are getting undefined behavior for 2nd case. Either you can use static int i OR use global variable (not preferred) OR use pointer to integer assignment.

Static or Pointer When "Returning" Array

I'm attempting to load an array of size n (user input), with random values. I've read that you can not return an array in C, you must use a pointer (Which is quite confusing). However, I've read that if you are storing that array to a local variable in the returning function, a pointer will not work and a static array can be used (can that be returned in a function?). Also, I've read that you are supposed to call free after using the array is open the space back up? I must be using it wrong because it crashed. So I commented it out for now. Some clarification would be great.
Here's what I have so far. When printing, it's just printing what I'm assuming is just garbage.
int* prefixAverages1(int);
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
int choice;
int input;
printf("What is the size of the array?:");
scanf("%d", &input);
printf("Do you want to run prefixAverages 1 or 2?");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Beginning prefixAverages1\n");
int *a = prefixAverages1(input);
for (int i=0; i < input; i++) {
printf("%d", &i);
printf("%d \n", a[i]);
}
//free(a);
break;
}
}
int* prefixAverages1(int input) {
int x[input];
int *a = (int*)malloc(input);
srand(time(NULL));
for(int i = 0; i < input; i++) {
int s = 0;
for(int j = 0; j < i; j++) {
int r = rand() % 100;
x[j] = r;
s = s + x[j];
}
a[i] = s / (i+1);
printf("%d \n", a[i]);
}
return a;
}
I'm aware my syntax may be wonky. I haven't touched C in years, so let me know if my error is syntaxical.
edit: Values are printing as intended in the function. Added print statement in code for clairity
I'm attempting to load an array of size n (user input), with random
values. I've read that you can not return an array in C, you must use
a pointer (Which is quite confusing).
Yes, the relationship between pointers and arrays and the surprisingly wide scope of things you cannot do with arrays themselves are common points of confusion. To some extent it's a pedantic distinction. Almost everything C allows you to do with an array, it makes you do via a pointer, but it automatically converts values of array type to appropriate pointers, so that those details are largely hidden.
But in some places it pokes out. For example, there is no valid syntax that allows you even to try to declare a function that returns an array.
In other places it is actively misleading. For example, you can declare a function that appears to accept an array as an argument, but the standard explicitly specifies that the argument is actually a corresponding pointer (and that's what naturally falls out when you call such a function anyway). Specifically:
int foo(int x[3]);
is 100% equivalent to
int foo(int *x);
However, I've read that if you
are storing that array to a local variable in the returning function,
a pointer will not work
That's not so much about arrays specifically, but rather about automatic variables in general. These logically cease to exist when they go out of scope -- at the end of the innermost block in which they are declared -- so pointers to or into such objects are no longer valid once the function returns. One way to obtain such a pointer value is for the function to return it. That in itself is OK, but you cannot safely dereference such a pointer value.
and a static array can be used (can that be
returned in a function?).
The lifetime of static variables of any type is the whole execution of the program. Therefore, it is safe and can be meaningful to return a pointer (in)to a static variable from a function. But although it can work to return a pointer to a static array from your function, you still cannot return such an array itself.
Also, I've read that you are supposed to
call free after using the array is open the space back up?
You should free memory that you have allocated with one of the memory allocation functions (malloc() etc.), and no other. But when you allocate memory inside a function, you can give the caller responsibility for freeing that memory by returning the pointer to it, among other ways.
In fact, most of what you demonstrate in your example code is fine in those regards. However, you do make a key error that undermines your program. Here:
int *a = (int*)malloc(input);
You allocate input bytes and store the pointer to them in a, but that is not enough storage for input objects of type int. The size of an int varies from implementation to implementation, but the minimum size permitted by the standard is two bytes, in the most common size is four bytes. To allocate space for input objects of type int, the basic idiom is
int *a = malloc(input * sizeof(int));
Personally, though, I prefer
int *a = malloc(input * sizeof(*a));
because then I get the correct size no matter what type the pointer's referenced type is, and even if I change it later.
The fact that you treated the allocated space as if it were larger than it really was likely explains much of your program's misbehavior, including the crash when you tried to free the allocated memory.
First of all malloc takes an inparam of no of bytes not absolute array size - so change this line:-
int *a = (int*)malloc(input);
to
int *a = malloc(input*sizeof(int));
Secondly, to debug incorrect values being printed put a print in your function prefixAverages1 :-
...
...
a[i] = s / (i+1);
printf("%d \n", a[i]);
...
In main print, get rid of the first print.. this is probably making you think printing incorrect values.. The address of the local loop counter variable will look like garbage
printf("%d", &i);
OR if you wanted to track the indexes of the array elements as well modify it to :-
printf("%d", i);
You must introduce the free back to avoid leaking memory
And you should follow #AustinStephens's suggestion and avoid using a second function
This works as far as having a function that loads an array with random values:
void randomValues(int arr[], int size);
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
int i;
int input;
int *array;
printf("What is the size of the array?: ");
scanf("%d", &input);
array = malloc(sizeof(int) * input);
randomValues(array, input);
for(i = 0; i < input; ++i)
printf("array[%d] = %d\n", i, array[i]);
free(array);
return 0;
}
void randomValues(int arr[], int size) {
int i;
int r;
srand((int) time(0));
for(i = 0; i < size; ++i) {
r = rand() % 100;
arr[i] = r;
}
}

how to copy returned array directly into another array?

I have been learning arrays, but theres one thing that I cant figure out.
I borrowed two books for C and looked online, but found no solution.
My function timesTen multiplies every array elemenet that I have by 10,
then returns pointer of that array back function main()
How can I copy array a[2] directly in array x[2]?
I would usually use for loop, but I cant, because arguments are in two different functions.
Solution has probably got something to do with pointers, so feel free to post sollution here, but is there any way around them aswell?
Heres the source code:
#include <stdio.h>
int timesTen(int a[])
{
int i;
for (i=0;i<2;i++)
{
printf("%d\t", a[i]);
a[i]*=10;
printf("%d\n", a[i]);
}
return a;
}
int main()
{
int i;
int x[2];
int a[2]={10,50};
// i know here's an error, but how do I fix it? I cant put x[0]=timesTen(a[0])
x[2] = timesTen(a);
//also what if there is array a[10], and I want to copy it in x[5]
for (i=0;i<2;i++)
printf("%d\n", x[i]);
return 0;
}
Thanks!
What you need to understand is the distinction between arrays and pointers. When you declare your two arrays in main(), you allocate two times memory for two integers. That's fine. But in C, you simply cannot pass arrays around (as in: implicitly allocate a new slap of memory and copy the data of the source array into this memory region). Instead, any array identifier will decay to a pointer to the first element of the array in almost all situation. So when you write
int x[2];
int a[2]={10,50};
timesTen(a);
this code is precisely equivalent to
int x[2];
int a[2]={10,50};
timesTen(&a[0]);
So, why does that not clash with your declaration of timesTen()? Because array parameters in function declarations decay right there, on the spot, into a pointer! So, your function declaration is precisely equivalent to this one:
int timesTen(int* a) {
This is one of the least understood features of the C language, and admittedly, it is hard to wrap your brain around this, but once you understand what pointer decay means, you will be much more at ease using pointers and arrays.
So, back to your question. Since you passed only a pointer to your array to timesTen(), and since you modify this array, the changes are directly visible in main(). There are two ways to achieve the behavior you want:
You can change the definition of timesTen() to copy the data into a destination array:
void timesTen(int size, int* source, int* dest) {
for(int i = 0; i < size; i++) dest[i] = 10*source[i];
}
int main() {
int x[2];
int a[2]={10,50};
timesTen(2, a, x); //pointer decay!
//x now contains {100, 500}
}
You can copy the data into the destination array before calling your function to modify the destination array:
void timesTen(int size, int* data) {
for(int i = 0; i < size; i++) data[i] = 10*data[i];
}
int main() {
int x[2];
int a[2]={10,50};
memcpy(x, a, sizeof(a)); //the sizeof operator is one of only two places where no pointer decay happens!
timesTen(2, x); //pointer decay!
//x now contains {100, 500}
}
In the function timesTen, since a is an array, each modification made to it in the function is also done to the parameter you passed (call by address not by value). Therefore you don't need to returns anything.
void timesTen(int a[])
{
int i;
for (i=0;i<2;i++) a[i]*=10;
}
And you just call it by:
timesTen(a);
You probably want something like this:
timesTen(a);
memmove(x, a, 2 * sizeof(x[0]));
instead of
x[2] = timesTen(a);
Note that your function does not need to return anything, because it is modifying the array on its original place. In C if you have an array parameter, it means that only a pointer is passed, not the whole array.
in main function:
int *p;
int i;
p = timesTen(a);
for ( i = 0; i < 2; i++ )
{
printf( "%d\n",*(p + i)); // here you can print the values returned from your function
}
Through pointers you could have eaisly managed it
main ()
{
int a[ 2 ];
int *ptr = timesTen(a);
for ( int i=0; i<2 ; i++)
{
printf("%d",ptr[i]);
}
And as far as
x[2] = timesTen(a);
Is concerned note that x[2] will give "value at 2nd adress from adrees of base that is x"
And it is not a variable but it is a value and you cant assign to a value.
Technically x[2] is not a lvalue.

function that returns an array (Win32 console application written in C, Learning about operating systems)

In C, is it not possible to make the return type an array? I'm starting to learn about pointers in my operating systems course and I need to make a function that takes 2 arrays as parameters and returns an array containing only the elements that are in both parameter arrays.
This is what I have so far for my C function that returns an array:
#include <stdio.h>
main()
{
printf("Hello world");
int array1[4] = {1, 2, 3, 4};
int array2[4] = {3, 4, 5, 6};
int* inter = intersection(array1, array2);
printf(inter); // <-- also, I don't know how I could get this to work for testing
//freezes program so it doesn't terminate immediately upon running:
getchar();
}
int* intersection(int array1[], int array2[])
{
int arrayReturn[sizeof(array1) + sizeof(array2)];
int count = 0;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if(array1[i]==array2[j])
{
arrayReturn[count] = array1[i];
count = count + 1;
}
}
}
return arrayReturn;
}
Another question I have is how could I test this function in the main() method using a printf() statement?
The reason why I need to do this is because we're learning about processes and memory allocation and pointers play a big role in OS development. My professor told me that pointers are so difficult to understand that they leave pointers out of many programming languages.
here we go
#include <stdio.h>
/* declare function, you need to capture array size as well, and also allow
to get result target pointer, result space info and pointer to place where the
size of result will be captured */
int* intersection(int * array1, int a1len , int * array2, int a2len, int* result, int *resultsize, int resultspace);
main()
{
printf("Hello world\n");
int array1[4] = {1, 2, 3, 4};
int array2[4] = {3, 4, 5, 6};
int arrayr[32]; /*result will be in this table */
int resultsize;
int resultspace = 32;
int i;
/* here comes confusion - int resultsize means it will be read as integer,
so we need to write &resultsize to get the pointer,
array declaration like int arrayr[number] is actually understood by system
as a pointer to an integer, pointing to first element of array,
allowing you to use indexes
so arrayr[3] actually means *(arrayr + 3 * sizeof(int))
*/
int* inter = intersection(array1, 4, array2, 4, arrayr, &resultsize, resultspace);
/* inter is now a pointer to arrayr */
for (i = 0; i<resultsize; i=i+1) {
printf("%d\n", inter[i]);
}
//freezes program so it doesn't terminate immediately upon running:
getchar();
}
int* intersection(int * array1, int a1len , int * array2, int a2len, int* result, int *resultsize, int resultspace)
{
/* as we received a pointer to resultsize (*resultsize)
we need to de-reference it using "*" to get or set the actual value */
*resultsize = 0;
int i, j;
for(i = 0; i < a1len; i++)
{
for(j = 0; j < a2len; j++)
{
if(array1[i]==array2[j])
{
result[*resultsize] = array1[i];
*resultsize = *resultsize + 1;
if (resultspace == *resultsize)
return result;
}
}
}
return result;
}
In C, is it not possible to make the return type an array?
No. Some of the characteristics that differentiate arrays from pointers are:
sizeof array evaluates to n * sizeof *array, where n is the number of elements, instead of the size of a pointer.
&array evaluates to a pointer to an array, instead of a pointer to a pointer.
You can use an array to initialise a pointer, eg. int *ptr = (int[]){ 1, 2, 3, 4 };, but you can't use a pointer to initialise an array, eg. int array[4] = ptr;.
You can't assign to an array eg. int array[4]; array = (int[]){ 1, 2, 3, 4 };, but you can assign to a pointer: int *ptr; ptr = (int[]){ 1, 2, 3, 4 };, unless the pointer is declared as a const pointer to int, eg. int * const ptr = NULL; ptr = (int[]){ 1, 2, 3, 4 };
I'm starting to learn about pointers in my operating systems course
and I need to make a function that takes 2 arrays as parameters and
returns an array containing only the elements that are in both
parameter arrays.
This isn't possible. Firstly, your array arguments are actually pointer arguments. Look at sizeof array1 and sizeof array2. Try to initialise an array with them. Try to assign to them. How many of the tests above seem to indicate that they're pointers? When you pass an array to a function, the array expression evaluates to a pointer to the first element of the array. Perhaps you'd want to declare your function to accept pointer to arrays, eg:
int *intersection(size_t sz1, int (*array1)[sz1], // array1 is a pointer to int[sz1]
size_t sz2, int (*array2)[sz2]) // array2 is a pointer to int[sz2]
{ ... }
Secondly, your function clearly returns a pointer value, not an array. Regarding that return value, arrayReturn is declared inside intersection as an array that has automatic storage duration, and so it will be destroyed when intersection returns. When main attempts to use that value, it'll be attempting to use a destroyed array. Returning an array using automatic storage duration isn't possible. Returning a fixed-size struct using automatic storage duration is possible, but this isn't helpful for your problem because your return value would need to be dynamic in size.
Another question I have is how could I test this function in the
main() method using a printf() statement?
You can't do anything with the return value of that function, because using an object that has been destroyed is undefined behaviour.
The reason why I need to do this is because we're learning about
processes and memory allocation and pointers play a big role in OS
development.
The C programming language is independant of OS implementations; It doesn't matter if an OS delays the destruction of objects with automatic storage duration. If you use a destroyed object, you're invoking undefined behaviour.
My professor told me that pointers are so difficult to understand that
they leave pointers out of many programming languages.
Has he/she written out his/her lesson plan? If not, then he/she is missing a crucial point where improvement can be identified. How successful has his/her written lesson plan been in the past? If it's been 100% successful, it doesn't make sense to be using words like "difficult"; Why would you want to unnecessarily trigger overwhelming feelings in students? If parts are too complex, then it makes more sense to identify and clarify those parts, rather than identifying those parts and specifying them as "difficult". It also makes no sense to mention other programming languages in a course about C.
When a professor's lesson plan becomes fairly successful, it becomes feasible to publish it as a book. One example is K&R's "The C Programming Language, Second Edition". Do you have a book?

Double array through pointers in C

I want to scan a 2D array with the help of pointers and have written this code, could you tell me why the compiler gives errors?
#include<stdio.h>
#include<stdlib.h>
int main(void) {
int i,j,n,a,b;
int (*(*p)[])[];
printf("\n\tEnter the size of the matrix in the form aXb\t\n");
scanf("%dX%d",&a,&b);
p=(int (*(*p)[b])[a])malloc(b*sizeof(int (*p)[a]));
for(i=0;i<b;i++) {
p[i]=(int (*p)[a])malloc(a*sizeof(int));
printf("\t\bEnter Column %d\t\n");
for(j=0;j<a;j++)
scanf("%d",&p[i][j]);
}
return 0;
}
This statement has several problems:
p=(int (*(*p)[b])[a])malloc(b*sizeof(int (*p)[a]));
First, malloc returns a void*. You are casting that pointer using (int (*(*p)[b])[a]) which yields a value, not a data type. That isn't a valid cast, so that's one reason that the compiler is yelling at you. At this point, p hasn't been initialized so the de-referencing taking place here can crash your program if this statement was executed.
Inside your malloc call, you are using sizeof(int (*p)[a]). The statement int (*p)[a] isn't a valid C statement.
It seems that you are making this a bit more complex that it needs to be. There are two ways of building a 2D array. You can build an array using malloc(a * b * sizeof(int)) as Reinderien explains. You can also build a 1D array of pointers, each pointing to an array of type int. From your code, it seems you are trying to do the latter.
The easier way to do this would be something like this:
int **p;
... get input from user ...
// Declare an array of int pointers of length b
p = malloc(b * sizeof(int*));
// For each int* in 'p' ...
for (i = 0; i < b; ++i) {
// ... allocate an int array of length 'a' and store a pointer in 'p[i]' ..
p[i] = malloc(a * sizeof(int));
// ... and fill in that array using data from the user
printf("\t\bEnter Column %d\t\n");
for(j = 0; j < a; j++)
scanf("%d", &p[i][j]);
}
Using this method of building a 2D array allows you to use the syntax p[x][y]. Since p is a pointer-to-pointer, p[x] is a pointer to an array and p[x][y] is an item in the pointed-to array.
That's some pretty contorted syntax. Usually when you make a 2D array:
The declaration is simply int *p;
The allocation is simply p = malloc(a*b*sizeof(int));
You cannot write p[i][j]. You must do one of several things - either make a secondary array int **q that contains row pointers to be able to write q[i][j] (better performance and legibility), or write p[b*i + j] (fewer steps).
Additionally, note that:
Your printf will spew garbage due to the missing %d parameter.
Since C is not typesafe, using scanf will hide any errors in indirection that you may make.
About the closest thing I could think of that remotely resembles what you were trying to do:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j;
const int a = 3, b = 4;
int m[4][3];
int (*p[4])[3];
for (i = 0; i < b; i++)
{
p[i] = &m[i];
printf("\t\bEnter Column %d\t\n", i);
for (j = 0; j < a; j++)
{
int x;
scanf("%d", &x);
(*p[i])[j] = x;
}
}
return 0;
}
It compiles and functions as expected, but it's pointlessly complicated. p is an array of pointers to arrays.

Resources