1

I am using turbo c when I declare and define the pointer k diffrently it gives the warning "nonportable pointer conversion " and the outcome for *k shows as garbage

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,*k;//declaration
int a[3][5] = {
{ 1, 2, 3, 4, 5 },
{6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }
}; *k = &a ; //defination
clrscr();
printf("%d\n",*k);//garbage value
printf("%d\n",*(k+2));//garbage value
printf("%d\n",*(k+3)+1);//garbage value
printf("%d\n",*(k+5)+1);//garbage value
printf("%d\n",++*k);//garbage value
getch();
}

where as when define and declare pointer k in same line it gives the result

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
int a[3][5] = {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }
}, *k = &a ;
clrscr();
printf("%d\n",*k);         //1
printf("%d\n",*(k+2));     //3
printf("%d\n",*(k+3)+1);   //5
printf("%d\n",*(k+5)+1);   //7
printf("%d\n",++*k);       //2
getch();
}

this problem is taken from "letusC".

Your response will be greatly appreciated!!

anki
  • 21
  • 1

2 Answers2

2

In first code, after declaration:

*k = &a ; //defination

Causes undefined behavior because k is uninitialized, pointing to a garbage location.

You should correct it as k = *a;

Whereas in second code you assign address at the time of declaration.

First, the type of &a is int(*)[3][5] and type of a is int(*)[5]. Type of *a is int[5] that can easily decays int int*

Second, the type of kis int* (and *k type is int) For expression *k = &a you may getting warning in both codes.

To assign address of first element in 2-D array; check following:

First-Code:

int *k;
int a[3][5] = {..........}; 
k = *a;

Check working code @codepade

Second-Code:

int a[3][5] = {.........}, *k = *a;

Check working code @codepade

To understand it read:

What does sizeof(&array) return? and
What does the 'array name' mean in case of array of char pointers?

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • Thanks Grijesh, for ur precious help int making my concept But even after i make k=a; code give error"can not convert int[3][5] to int *" – anki Oct 25 '13 at 16:14
  • @anki suggestion `k =a` was wrong, my mistake, check updated answes with links of working codes. – Grijesh Chauhan Oct 26 '13 at 03:07
  • Thanks @Grijesh now i understands** thanks for ur help** hope u will keep answering to the problems(for others too). – anki Oct 26 '13 at 06:34
  • @anki Yes I will answer (if I will be able to answer)...My suggestion is for you don't read LetUs-C It is outdated a dos based book. – Grijesh Chauhan Oct 26 '13 at 06:37
  • @anki Pick a book from this link: [The Definitive C Book Guide and List](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) – Grijesh Chauhan Oct 26 '13 at 06:39
0

int *k = &a; is the same as int *k; k = &a;, not int *k; *k = &a;.