Reputation: 7386
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!!
Upvotes: 0
Views: 161
Reputation: 183883
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");
}
Upvotes: 2
Reputation: 13542
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]);
Upvotes: 0