user14570759
user14570759

Reputation:

why does the string get printed out as an argument? in c

why does the string "test" get printed out as an argument?

i am not passing a pointer to the string since i haven't allocated it before the argument

does the string argument "test" get stored somewhere i the memory heap?

void printAstring(char * string){
    printf("%s",string);
}

 printAstring("test"); //Prints out test

usually if i want to pass a string as an argument to a pointer as char parameter i allocate the array of char and then pass it


void printAstring(char * string){
    printf("%s",string);
}

char printThis[5]="test";

 printAstring(printThis); //Prints out test

Upvotes: 0

Views: 66

Answers (2)

Steve Summit
Steve Summit

Reputation: 47933

Almost without exception when you write anything between double quotes, like this:

"string literal"

you are creating (you are asking the compiler to create) a read-only, anonymous array of char, of just the right size, initialized to contain that string. And then since you're using this anonymous array in an expression where you need its value (in this case, so you can pass it to the printAsString function), the compiler automatically generates a pointer to the array's first element, just as it does for any array when you try to use its value.

In other words, when you wrote

printAstring("test");

what you got was more or less exactly as if you had written

const char __anonymous_array[] = "test";
printAstring(&__anonymous_array[0]);

The string (the anonymous array) is not stored on the heap, though; it's typically stored either with the program's initialized data, or perhaps (since it's readonly) with its code.

Upvotes: 1

dbush
dbush

Reputation: 223739

A string constant is actually a char array stored in a read-only portion of memory. So when you pass it to printAsString you're passing the address of the first element of the array where the string constant is stored.

Upvotes: 0

Related Questions