Home > Software design >  Is it possible to point a char pointer to a whole string as I need the string to be printed?
Is it possible to point a char pointer to a whole string as I need the string to be printed?

Time:08-13

C function to remove the first string from an XOR linked list of names:

int remove_string(Node **head, char *deleted_string) {
    Node *temp = *head;
    *deleted_string = *(*head)->name;
    *head = calculate_xor_value(NULL, temp->xor_value);
    if (*head != NULL) {
        (*head)->xor_value = calculate_xor_value(NULL, calculate_xor_value(temp, (*head)->xor_value));
    }
    free(temp);
}

In the question, one of the input parameters has to be a char pointer called deleted_string, which is the string that is being removed from the list. The code to remove the string works fine (line 4 onwards), but I am struggling to save the string to the char* deleted_string (line 3) *deleted_string = *(*head)->name;

Everytime I run the code // printf("%s", deleted_string ); only the first character is being printed; I think I understand that this is because pointers only point to the first character of a string, but is there a way to make the pointer point to the whole string? Perhaps by somehow converting (*head)->name to a string or an array?

Any help would be appreciated, sorry if this is a silly question. I have spent hours trying to find another page about this but I didn't so I thought I'd ask.

CodePudding user response:

Assuming (*head)->name is of type char*, you are dereferencing both the char *deleted_string and char *name, hence operating on something of type char.

The line

*deleted_string = *(*head)->name; 

is equivalent of doing something like

char a;
char b = 0;

a = b;

If you want to copy the contents of (*head)->name into the deleted_string, you can use strcpy or strncpy like,

strncpy( deleted_string, (*head)->name, SIZE );

Where the SIZE is whatever maximum size the deleted_string can hold. strcpy is the same, just without the size argument.

As comments suggested, both should be used with care, as strcpy can attempt to copy more characters than the destination can hold, causing write violations, and strncpy will truncate if the source is bigger than the destination, the resulting string will not necessarily be null-terminated. In such case, functions that assume the string is null-terminated will misbehave, such as printf( "%s" ... ), causing read violations. For more information, you can check this post.

  • Related