int main()
{
char *p = "hello all ";
printf(p);
}

I thought the above code should ve showed a compile time error. but it din , any reason how it worked?

Do you also think this should be an error?

printf("hello world");

the memory at the address pointed to by 'p' has been assigned the values shown. therefore, you can print the null terminated string as you might expect.

but the memory has not been allocated, so if you try to modify it the resulting behaviour is undefined.

at least that's how i understand it. someone else can clarify if i'm missing something.


.

but the memory has not been allocated, so if you try to modify it the resulting behaviour is undefined.
.

The problem is NOT that memory was not allocated for the string (actually it was), but that the string resides in (probably) read-only memory, depending on how the compiler chooses to handle it. Its never advisable to try and modify string literals.

int main()
{
char *p = "hello all ";
printf(p);
}

I thought the above code should ve showed a compile time error. but it din , any reason how it worked?

You are mistaken. int printf ( const char * format, ... ); is the prototype. You passed it the proper argument.

^^ thanks, A.D. apparently i need to revisit memory allocation..

More precisely: if the program attempts to modify an array corresponding to a string literal, the behavior is undefined.

thank you .. this clears all the doubt

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.