deferencing the int malloc pointer - c

int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int rslt, n;
float sum = 0;
scanf("%d", &n);
int *tri = (int*)malloc(n * 3 * sizeof(int));
if(tri == NULL){
return 1;
}
printf("%d\n", *(tri[0]));
when I am referencing the tri pointer then it is showing the error.
invalid type argument of unary '*'.
thanks for the answer.
The above part is clarified but I have another issue. but I have another issue
int main()
{
int rslt, n;
float sum = 0;
scanf("%d", &n);
int *tri = (int*)malloc(n * 3 * sizeof(int));
if(tri == NULL){
return 1;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 3; j++)
{
scanf("%d", &(tri[j]));
}
printf("\n");
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 3; j++)
{
sum += tri[j] / 2;
printf("%d %d\n",sum,tri[j] / 2);
}
}
printf("%d\n",sum);
return 0;
}
when I am printing the tri[j] it is showing some garbage value.

The variable tri has the type int * due to this declaration
int *tri = (int*)malloc(n * 3 * sizeof(int));
Pay attention to that you allocated an uninitialized memory.
The expression tri[0] has the type int. And you are trying to apply the dereference operator to the expression of the type int
*(tri[0])
So the compiler issues an error.
Instead you could write
int *tri = (int*)calloc(1, n * 3 * sizeof(int));
and then write either
printf("%d\n", tri[0]);
or
printf("%d\n", *tri);
These for loops
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 3; j++)
{
scanf("%d", &(tri[j]));
}
printf("\n");
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 3; j++)
{
sum += tri[j] / 2;
printf("%d %d\n",sum, tri[j] / 2);
}
}
printf("%d\n",sum);
are incorrect. There are used an incorrect conversion specifier %d instead of %f with the variable sum and incorrect expressions for indices. You need to write
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 3; j++)
{
scanf("%d", &(tri[3 * i + j]));
}
printf("\n");
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 3; j++)
{
sum += tri[3 * i + j] / 2;
printf("%f %d\n",sum, tri[3 * i + j] / 2);
}
}
printf("%f\n",sum);

The array expression a[i] is defined as *(a + i) - given some address value a, offset i elements (not bytes!) from that address and dereference the result, so
*tri == *(tri + 0) == tri[0]
The expression tri[0] has type int, which is why the compiler is complaining when you write *(tri[0]); the operand of the unary * operator must have a pointer type.
So in your printf statement you would use either *tri or tri[0]. The type of either expression is int.
As others have said, malloc does not initialize the allocated memory, so the value of tri[0] may be anything. You could use calloc instead, which initializes the memory to all-bits-zero:
int *tri = calloc( n, sizeof *tri );
In C you do not need to cast the result of malloc, calloc, and realloc1, and most of us will advise you to not do so. Similarly, since the type of the expression *tri is int, the result of sizeof *tri is the same as sizeof (int). This way you don't have to worry about keeping types straight between the declaration, the cast, and the sizeof expression, so you're less likely to make a mistake.
This is not the case in C++, but if you're writing C++ you shouldn't be using the C *alloc functions anyway.

Related

memory alocation with 2D Array

I am facing a question in which I am required to create a function that gets a 2D array and it's size and it should return another 2D array which is basically the same one but half rows size and half columns size and each group of arrays depending on the size of the original matrix will be pasted next to each other, example:
https://imgur.com/a/ctRUopc
image of the faulty output i am getting :
https://imgur.com/a/85q8ipe
it keeps giving me trash value after the second matrix paste for some reason and i dont know why :/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
long long Power(long long C1, long long C2)
{
int Digit = 0, i = 0;
long long Flag, DigitCount=0, Multiplier = 1;
Flag = C2;
while (Flag != 0)
{
Digit = Flag % 10;
DigitCount++;
Flag = Flag / 10;
}
while (i < DigitCount)
{
Multiplier = Multiplier * 10;
i++;
}
long long Final = 0;
Final = (Multiplier * C1) + C2;
return Final;
}
long long** shrink(long long** Matrix, int size, int* pSize)
{
if (size % 2 != 0)
{
return 0;
}
*pSize = size / 2;
long long A, B, C;
long long **New_Matrix = 0;
New_Matrix = (long long**)malloc(*pSize * sizeof(long long*));
for(int i=0; i<*pSize; i++)
{
New_Matrix[i] = (long long*)malloc(*pSize * sizeof(long long));
for (int j = 0; j < *pSize; j++)
{
A = Power(Matrix[2 * i][2 * j], Matrix[2 * i][2 * j + 1]);
B = Power(A, Matrix[2 * i + 1][2 * j]);
C = Power(B, Matrix[2 * i + 1][2 * j + 1]);
}
}
return New_Matrix;
}
int main()
{
long long** Matrix = 0;
int size;
int *pSize;
long long** result=0;
printf("Size Insertion : \n");
scanf("%d", &size);
Matrix = (long long**)malloc(size * sizeof(long long*));
printf("Matrix Insertion : \n");
for (int i = 0; i < size; i++)
{
Matrix[i] = (long long*)malloc(size * sizeof(long long));
for (int j = 0; j < size; j++)
{
scanf("%lld", &Matrix[i][j]);
}
}
printf("Matrix Display : \n");
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
printf("%lld ", Matrix[i][j]);
}
printf("\n");
}
result = shrink(Matrix, size, &pSize);
for (int i = 0; i < pSize; i++)
{
for (int j = 0; j < pSize; j++)
{
printf("%lld ", result[i][j]);
}
printf(" \n");
}
free(result, Matrix);
return 0;
}
result = shrink(Matrix, size, &pSize)
Here you're passing the address of the pSize pointer to the function, which when dereferenced, returns the underlying pointer. So the line
*pSize = size / 2; assigns the value to the underlying pointer which is simply wrong. Pointers only hold memory addresses. You may probably have meant to have written this:
**pSize = size / 2;
You should dereference once to get the underlying pointer, twice to get to the variable it points to.
Also, you need to dereference pSize in the for loops as well to get the size value set by the function
for (int i = 0; i < *pSize; i++)
{
for (int j = 0; j < *pSize; j++)
{
printf("%lld ", result[i][j]);
}
printf(" \n");
}
Also, pSize is an empty pointer, it points to an undefined memory address. Make sure that's not the case:
int * pSize = (int *) malloc(sizeof (int));
// rest of code
free(pSize);

Understanding Array of pointers

I am doing something like this;
int main()
{
int *b[2], j;
for (j = 0; j < 2; j++)
{
b[j] = (int *)malloc(12 * sizeof(int));
}
return 0;
}
Please tell me what this instruction really means? And how can I pass this array of pointers to a function to access values like *(B[0]+1),*(B[1]+1) etc?
int main(void)
{
int *b[2], j; // initialization of an array of pointers to integers (size = 2)
for (j = 0; j < 2; j++) // for each of the pointers
{
b[j] = malloc(12 * sizeof (int)); // allocate some space = 12 times size of integer in bytes (usually 4)
}
return 0;
}
If you want to pass this array to a function you can just pass b
foo(b);

counting negative integers in a matrix

i am having error while running this code
negativenoinmatrix.c:10:16: error: subscripted value is neither array nor pointer nor vector
if(z[i][j]<0)
i want to calculate the number of negative integers in a matrix
#include <stdio.h>
int negnumbers(int *z, int n, int m)
{
int count = 0;
int i = 0;
int j = m - 1;
while (j >= 0 && i < n)
{
if (z[i][j] < 0)
{
count += (j + 1);
i += 1;
}
else
j -= -1;
}
return count;
}
int main()
{
int n = 3, m = 4;
int a[n][m];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
scanf("%d", &a[i][j]);
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
printf("%d ", a[i][j]);
printf("\n");
}
int val = negnumbers((int *) a, 3, 4);
printf("%d", val);
}
The function needs to accept a pointer to an array, not a pointer to a single item. Change it to
int negnumbers(int n, int m, int z[n][m])
...
int val = negnumbers(3, 4, a);
(Where int z[n][m], as per the rule of "array adjustment", will get changed by the compiler internally to a pointer to the first element, int (*z)[m].)
When you pass a 2-d array to a function, at least the 2nd dimension must be specified. Change to this:
int negnumbers(int z[][4],int n,int m)
You can then use this more straightforward approach to counting the negative numbers:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (z[i][j] < 0)
count++;
}
}
You are calling a pointer z, and also creating a dynamic matrix out of it. So you need to allocate some memory for it which can be done with:
malloc(z[i][j])
Then after you're done, make sure you deallocate the memory now or else you'll have a memory leak, which you can read more about at Memory Leaks wikipedia.
This is done by calling free(...)
Hope this solves the not an array or pointer error!

Pointer to Pointer to integer

i'm using a pointer to pointer to intger as a 2 Dims array, i wrote these code but i failed on getting the integer value.
#include<stdio.h>
#include<conio.h>
void main(void)
{
int **pptr = 0, size = 0, size2 = 0, i, j;
clrscr();
printf("Enter Size of Main Store n");
scanf("%d", &size);
pptr = (int **) malloc(size * sizeof(int *));
printf("Enter Size of Sub Store n");
scanf("%d", &size2);
for (i = 0; i < size; i++) {
pptr[i] = (int *) malloc(size2 * sizeof(int));
}
printf("Enter Values n");
for (i = 0; i < size; i++) {
for (j = 0; j < size2; j++) {
scanf("%dn", pptr[i][j]);
}
}
clrscr();
printf(" Valuesn");
for (i = 0; i < size2; i++, pptr++) {
printf("%dn", *pptr + i);
}
getch();
}
it prints rubbish!!
scanf("%d", arg) expects a pointer to int, but
for (i = 0; i < size; i++) {
for (j = 0; j < size2; j++) {
scanf("%dn", pptr[i][j]);
}
}
you pass it an int, an uninitialised int at that. The indeterminate value in that memory location is then interpreted as a pointer, and the scan tries to store the converted value who-knows-where. It is not unlikely that that will cause a segmentation fault.
You should pass &pptr[i][j] as the argument there.
for (i = 0; i < size2; i++, pptr++) {
printf("%dn", *pptr + i);
}
prints the int* *pptr +i, which is &pptr[0][i], using the %d format that expects an int argument.
You should
printf("%d\n", pptr[0][i]);
if you want to print the values of the diagonal (as seems to be the case, since you also increment pptr in the loop), or, better
for(i = 0; i < size && i < size2; ++i) {
printf("%d\n", pptr[i][i]);
}
or, if you want to print the entire grid,
for(i = 0; i < size; ++i) {
for(j = 0; j < size2; ++j) {
printf("%d ", pptr[i][j]);
}
printf("\n");
}
scanf takes a int *, not an int. So...
scanf("%dn", pptr[i][j]);
should be:
scanf("%dn", &(pptr[i][j]));
or it could be:
scanf("%dn", (pptr[i]+j));
also, printf needs a value (int), not a pointer. So...
printf("%dn", *pptr + i);
should probably be something like:
printf("%dn", *(*pptr+i));
or the much nicer looking equivalent:
printf("%dn", pptr[0][i]);

Allocating dynamic 2D char array

gcc 4.6.2 c89
Allocating memory for a 2D array and filling with characters.
However, I don't seem to be filling as when I print nothing is displayed.
Am I doing something wrong here?
char **attributes = NULL;
/* TODO: Check for memory being allocated */
attributes = malloc(3 * sizeof(char*));
int i = 0;
int k = 0;
for(i = 0; i < 3; i++) {
for(k = 0; k < 5; k++) {
sdp_attributes[i] = malloc(5 * sizeof(char));
sdp_attributes[i][k] = k;
}
}
for(i = 0; i < 3; i++) {
for(k = 0; k < 5; k++) {
printf("attributes[i][k] [ %c ]\n", attributes[i][k]);
}
}
Many thanks for any advice,
Two major issues:
First Issue:
for(i = 0; i < 3; i++) {
for(k = 0; k < 5; k++) {
sdp_attributes[i] = malloc(5 * sizeof(char));
You are reallocating sdp_attributes[i] at each iteration of the inner loop - thereby overwriting it each time. You probably wanted this instead:
for(i = 0; i < 3; i++) {
sdp_attributes[i] = malloc(5 * sizeof(char));
for(k = 0; k < 5; k++) {
Second Issue:
sdp_attributes[i][k] = k;
You are basically writing the lower ascii characters. Most of them are not printable.
Something like this might do what you want:
sdp_attributes[i][k] = k + '0';
You probably want:
for (i = 0; i < 3; i++)
{
attributes[i] = malloc(5 * sizeof(char));
for (k = 0; k < 5; k++)
{
attributes[i][k] = k;
}
}
This ignores error checking on the allocation.
It also fixes the name of the array to match the declaration, but your code either wasn't compiling (don't post non-compiling code unless your question is about why it doesn't compile!) or you have another variable called sdp_attributes declared somewhere which you weren't showing us.
Your code was leaking a lot of memory. Each time around the k-loop, you allocated a new array of 5 characters and stored the pointer in attributes[i] (or sdp_attributes[i]), storing the new pointer over what was there before, so you overwrote the value of the first 4 pointers. You could not possibly free the first four items - they were lost irretrievably. Also, on the last iteration, you initialized the 5th element of the final array, but the previous 4 were not initialized and therefore contained indeterminate garbage.
Also, in your printing loop, the values in the array are control characters ^#, ^A, ^B, ^C and ^D; these do not necessarily print well with %c (especially not ^#, which is also known as NUL or '\0'). The printf() statement might be better written as:
printf("attributes[%d][%d] [ %d ]\n", i, k, attributes[i][k]);
This prints the array indexes (rather than simply the characters [i][k] for each entry), and prints the control characters as integers (since the char values are promoted to int when passed to printf()) rather than as control characters.
(It's also more conventional to use i and j for a pair of nested loops, and i, j, and k for triply nested loops, etc. However, that's a very minor issue.)
for(i = 0; i < 3; i++) {
for(k = 0; k < 5; k++) {
sdp_attributes[i] = malloc(5 * sizeof(char));
sdp_attributes[i][k] = k;
}
}
Your erasing the allocated memory every time you loop in the inner most loop.
Here is a correct version.
for(i = 0; i < 3; i++) {
sdp_attributes[i] = malloc(5 * sizeof(char));
for(k = 0; k < 5; k++) {
sdp_attributes[i][k] = k;
}
}
And you should fix your declaration:
attributes = malloc(3 * sizeof(char*));
to
sdp_attributes = malloc(3 * sizeof(char*));
Don't forget to free up all the memory allocated
for(i = 0; i < 3; i++)
{
free(sdp_attributes[i]);
}
free(sdp_attributes);
The correct way to allocate and assign elements to 2d array is as follows (but this is a int array, you can try and change it for char array):
One thing to note: As mentioned by #Mysticial, you should add/subtract '0' to your int value to get the char value when using ASCII character set (remember our itoa() functions!).
#include <stdio.h>
#include <stdlib.h>
int main()
{
int row, column;
int **matrix;
int i, j, val;
printf("Enter rows: ");
scanf("%d", &row);
printf("Enter columns: ");
scanf("%d", &column);
matrix = (int **) malloc (sizeof(int *) * row);
for (i=0 ; i<row ; i++)
matrix[i] = (int *) malloc (sizeof(int) * column);
val=1;
for (i=0 ; i<row ; i++) {
for (j=0 ; j<column; j++) {
matrix[i][j] = val++;
}
}
for (i=0 ; i<row ; i++) {
for (j=0 ; j<column; j++) {
printf("%3d ", matrix[i][j]);
}
printf("\n");
}
for (i=0 ; i<row ; i++)
free(matrix[i]);
free(matrix);
return 0;
}
Few points to note:
error handling should be added for malloc()
malloc()'ed memory must be free()'ed

Resources