Many times we talk about undefined, unspecified and implementation-defined behavior in c
. However, what is the difference between these concepts?
Home
/
user-86138
Maur's questions
Maur
Asked:
2020-05-12 03:30:45 +0800 CST
1st code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct{
int edad;
char *ptr;
}hola;
int main(){
hola.edad=2;
printf("%d\n",hola.edad);
hola.ptr=malloc(5);
strcpy(hola.ptr,"Hola");
printf("%s",hola.ptr);
free(hola.ptr);
return 0;
}
2nd code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct hola{
int edad;
char *ptr;
}holas;
int main(){
holas.edad=2;
printf("%d\n",holas.edad);
holas.ptr=malloc(5);
strcpy(holas.ptr,"Hola");
printf("%s",holas.ptr);
free(holas.ptr);
return 0;
}
What difference would it make to declare one struct
like in the first example,
struct{
int edad;
char *ptr;
}hola;
... or declare it like in the second example?
struct hola{
int edad;
char *ptr;
}holas;
Is the second one clearer when putting a name to the struct
?
Maur
Asked:
2020-05-09 11:56:03 +0800 CST
Why is it safe to return string2? At the end of the function, the stack frame would not be overwritten? I've seen many compilers store the literal "hello" in a read-only area of memory, is that why it's safe to return string2 without the stack frame being overwritten?
A greeting and thanks in advance
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *imprimir_cadena( char *cadena2 ) {
return cadena2;
}
int main( ){
char *ptr = "hola";
char *p = imprimir_cadena( ptr );
printf( "%s", p );
return 0;
}