-2

How can I make this code work. Address in main is different inside func as well as the value is not the sam ?

const char *Like="CO";
void main(){
 printf("%d",Like); // o/p 4206935
 printf("%c\n\n",(Like[0]));   // o/p C
 func(conLen);
}
void func(const char *chP){
printf("%d",chP); // o/p  4206938
printf("%c\n\n",(chp[0]));  // o/p  %
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 4
    Argument `conLen` is unrelated to `Like` and is not defined in the code anyway. – Jonathan Leffler Apr 14 '21 at 17:12
  • @Anter The variable chp is not declared. – Vlad from Moscow Apr 14 '21 at 17:15
  • 3
    Please keep the return type of `main` to be `int` , `main` can never have a return type of `void`,`conLen` is undefined declare and assign it somewhere – Abhilekh Gautam Apr 14 '21 at 17:15
  • Additionally, `%d` is an incorrect field directive for a pointer. Use `%p`, instead: `printf("%p", (void *) Like);`. – John Bollinger Apr 14 '21 at 17:16
  • @AbhilekhGautam — on Windows, `void main()` is a documented and hence acceptable form for `main()` — as in, the compiler will accept it. It is better not to use it, but be careful of overstating your case. See [What should `main()` return in C and C++?](https://stackoverflow.com/q/204476/15168) for more details. – Jonathan Leffler Apr 14 '21 at 17:49

3 Answers3

3

The presented program shall not compile at least because there are used several undeclared names.

How can I make this code work. Address in main is different inside func as well as the value is not the sam ?

It seems you are trying to achieve something like the following

#include <stdio.h>

const char *Like = "CO";

void func( const char *chP );

int main(void) 
{
    printf( "%p\n", ( void * )Like );
    printf( "%c\n", Like[0] );
    func( Like );
}

void func( const char *chP )
{
    printf( "%p\n", ( void * )chP );
    printf( "%c\n", chP[0] );
}

The program output might look like

0x555a23f0d004
C
0x555a23f0d004
C

As you can see the outputted addresses and values in main and in the function func are the same.

Pay attention to that to output a value of a pointer you should use the conversion specifier p.

And according to the C Standard the function main without parameters shall be declared like

int main( void )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
3

If you are talking about passing and accessing a pointer (char*) you can easily do it the following way:

#include<stdio.h>

void func(char*);
int main(){

char* Like ="hello";
func(Like);

return 0;

}

void func(char* a){

printf("The string is %s",a);

}
Abhilekh Gautam
  • 648
  • 1
  • 11
  • 27
-1

I am assuming that you want to pass the pointer to the function

while calling the function func pass the pointer with it like func(Like)

Apologies, if I didn't understand your question correctly.