user3001566 user3001566 - 3 months ago 9
C Question

C Programming , Changing String Value in function without passing the size as parameter

i have a question, i know the following implementation works correctly :

void editMessage(char* message , int sizeOfMessage){
char newMessage[] = "modified";

printf("size of message is %lu \n",sizeof(message));
printf("size of new message is %lu \n",sizeof(newMessage));

if (sizeof(newMessage) <= sizeOfMessage) {

for (int i=0 ; i < sizeof(newMessage); i++) {

message[i] = newMessage[i];

}

} else {
printf("size of new message is too big\n");
}

}

int main() {

char randMessage[] = "original message";
editMessage(randMessage,sizeof(randMessage));
printf("the value of randMessage after function call is %s \n",randMessage);
return 0;
}


but if i want to change the string value in function without passing the size of pointer, is it possible? if yes , how? if not , why not?

i mean i am looking to change above editMessage Function something like this :

void editMessage(char* message){
char newMessage[] = "modified";

printf("size of message is %lu \n",sizeof(message));
printf("size of new message is %lu \n",sizeof(newMessage));

if (sizeof(newMessage) <= sizeOf(message)) {

for (int i=0 ; i < sizeOf(message); i++) {

message[i] = newMessage[i];

}

} else {
printf("size of new message is too big\n");
}

}


and the call in the main like this

editMessage(randMessage);


why this is not working , could one please explain in details , and then i would accept his response?
Thanks!

Answer

sizeOf(message) will not work. sizeOf(message) will give the size of the variable message, and since originally message is a pointer you will get the size of a pointer.


Since it is a NUL terminated string, you can get the length of the string by using strlen() and use that in your function.


So, your code should look something like this,

  void editMessage(char* message){
    char newMessage[] = "modified";
    int size = strlen(message);

    printf("size of message is %d \n", size);
    printf("size of new message is %lu \n",sizeof(newMessage));

    if (sizeof(newMessage) <= size) {

        for (int i=0 ; i < size; i++) {

            message[i] = newMessage[i];

        }

    } else {
        printf("size of new message is too big\n");
    }

}

For an array of char which is not terminated by NUL, there is no way to find out the length other then sending the length of the array of char as a parameter.

Therefore, in the calling function you need to keep track of the number of chars you are writing in the array (to know the length).

Notice I am not saying string because an array of char becomes a string only when it is terminated by a NUL character.


NOTE:

Use the standard definition of main()

int main(void) //if no command line arguments.
Comments