K
karthikbalaguru
Hi,
I got an interesting output w.r.t array
manipulation. I have listed the 2 kind
of approaches that were used for
analysis.
Approach 1
-------------------
#include<stdio.h>
int main(void)
{
char a[]="12345\\0";
char *b = "12345\\0";
int i=strlen(a);
int j=strlen(b);
printf("Here i is %d , j is %d\n",i,j);
while(*b!='\0')
{
printf("*b is %c \n",*b++);
}
while(*a!='\0')
{
printf("*a is %c \n",*a++);
}
return 0;
}
For Approach 1, i got the below error message -
error C2105: '++' needs l-value
Approach 2
-----------------
#include<stdio.h>
void incre(char a[]);
int main(void)
{
char a[]="12345\\0";
char *b = "12345\\0";
int i=strlen(a);
int j=strlen(b);
printf("Here i is %d , j is %d\n",i,j);
while(*b!='\0')
{
printf("*b is %c \n",*b++);
}
incre(a);
return 0;
}
void incre(char a[])
{
while(*a!='\0')
{
printf("*a is %c \n",*a++);
}
}
For approach 2, I got the output as below -
Here i is 7 , j is 7
*b is 1
*b is 2
*b is 3
*b is 4
*b is 5
*b is \
*b is 0
*a is 1
*a is 2
*a is 3
*a is 4
*a is 5
*a is \
*a is 0
The manipulation of the base address of the array
shows error if done in main but it works fine if
done in a function.
Is the correct output in Approach 2, is a kind of undefined
behaviour that gives correct output ?
AFAIK, the base address manipulation is not
possible in C language and the compiler does not
allow to do it. But, the output from the approach 2,
seems to convey a different info. Strange !!
Any ideas ?
Thx in advans,
Karthik Balaguru
I got an interesting output w.r.t array
manipulation. I have listed the 2 kind
of approaches that were used for
analysis.
Approach 1
-------------------
#include<stdio.h>
int main(void)
{
char a[]="12345\\0";
char *b = "12345\\0";
int i=strlen(a);
int j=strlen(b);
printf("Here i is %d , j is %d\n",i,j);
while(*b!='\0')
{
printf("*b is %c \n",*b++);
}
while(*a!='\0')
{
printf("*a is %c \n",*a++);
}
return 0;
}
For Approach 1, i got the below error message -
error C2105: '++' needs l-value
Approach 2
-----------------
#include<stdio.h>
void incre(char a[]);
int main(void)
{
char a[]="12345\\0";
char *b = "12345\\0";
int i=strlen(a);
int j=strlen(b);
printf("Here i is %d , j is %d\n",i,j);
while(*b!='\0')
{
printf("*b is %c \n",*b++);
}
incre(a);
return 0;
}
void incre(char a[])
{
while(*a!='\0')
{
printf("*a is %c \n",*a++);
}
}
For approach 2, I got the output as below -
Here i is 7 , j is 7
*b is 1
*b is 2
*b is 3
*b is 4
*b is 5
*b is \
*b is 0
*a is 1
*a is 2
*a is 3
*a is 4
*a is 5
*a is \
*a is 0
The manipulation of the base address of the array
shows error if done in main but it works fine if
done in a function.
Is the correct output in Approach 2, is a kind of undefined
behaviour that gives correct output ?
AFAIK, the base address manipulation is not
possible in C language and the compiler does not
allow to do it. But, the output from the approach 2,
seems to convey a different info. Strange !!
Any ideas ?
Thx in advans,
Karthik Balaguru