I know that my questions are very simple but googleing them didn't get me any useful results... They'r probably too simple!!
No. 1
char* createStr(){
char* str1 = malloc(10 * sizeof(char));
printf("str1 address in memory : %p\n", &str1);
return str1;
}
int main(void){
char* str2 = createStr();
printf("str2 address in memory : %p\n", &str2);
}
Result:
str1 address in memory : 0x7fffed611fc8
str2 address in memory : 0x7fffed611fe8
Why are the addresses different in and out of the createStr() function and how can I free(str1)???
No. 2
int main(int argc, int *argv[]){
printf("Basename is %s ", (char*) argv[0]);
if(argc > 1 ){
printf("and integer arg is : %d.\n", (int) *argv[1]);
}
}
If I compile and run $ ./test 3
, how can I get int 3?
Result:
Basename is ./test and integer arg is : 1380909107.
To fix the first one:
Otherwise, you're printing out the address of the variable (
str1
andstr2
), not the address the variable is pointing to.I've also added a call to
free()
to fix the memory leak.As to the second one, you need to use
atoi()
to convert the string to anint
:For the second exemple :
*argv[1]
is achar *
(i.e"3"
)If you want to display
"3"
you have to useprintf("%s\n", *argv[1]);
or get an integer from the string usingatoi()
.Maybe you can even try to write your own version of
atoi()
!Comments inline!
No. 1
No 2.
Point to note:
char * argv[]
and notint * argv[]
Question 1:
The addresses are different because you are taking the addresses of the pointers, not the addresses of the variables held by the pointers. Since
str2
exists on the stack ofmain
andstr1
on the stack ofcreateStr
, their addresses are different.You can free
str1
by freeingstr2
, because they point the same location. The address thatstr1
points to is copied insidestr2
whenstr1
is returned fromcreateStr
.Question 2:
Use
int value = atoi(argv[1]);
This converts achar*
to anint
.The first example allocates the string, then returns a pointer to it. When you do the assignment from the method's return value, you just assign the pointer. You only ever made one string.
In the second example, you want
atoi
.