Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function argument char * vs char []

I think this question is an extension of this SO answer. Say I have the following code:

#include <stdio.h>
#include <string.h>

void func(char *str)
{
    strcpy(str, "Test");
}

int main()
{
    char testStr[20] = "Original";
    func(testStr);
    printf("%s\n", testStr);  /* Prints "Test" followed by a new-line */
    return 0;
}

By my understanding, shouldn't func expect a pointer to a read-only literal as an argument? Whereas, what is being passed is a copy on the stack of a read-only literal.

Even though this yields correct results, is doing this 100% correct? Would it improve readability of code if func() accepted char [] instead of char *?

like image 592
Anish Ramaswamy Avatar asked Feb 17 '23 02:02

Anish Ramaswamy


1 Answers

Your understanding is correct. The code is fine.

The following, on the other hand, isn't:

void func(char *str)
{
    strcpy(str, "Test");
}

int main()
{
    char* testStr = "Original";
    func(testStr);
}

This attempts to modify a string literal, resulting in undefined behaviour.

As to the question of readability, that's subjective.

like image 130
NPE Avatar answered Feb 19 '23 14:02

NPE