0

Just like the title says, I'm trying to see if I could assign a variable that contains a string to another variable that contains a string.

For example:

printf("Enter word to search in file: ");
scanf("%s", word);
word = words;

In this case, the string in word would be assigned to the string in words.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • You've not shown how either `word` or `words` is defined. That's crucial information, though. You need to know whether there is anything special to be done with the 'old' data pointed at by `word`. If it is a local array, you don't have to release it; if it is a pointer to space allocated with `malloc()`, you probably need to free it. If you have a simple array, you have to use `strcpy()`. If you are using dynamic memory allocation, you may be able to use a simple pointer assignment. If the `word` space is a function parameter, you have to define what the function doing the reading expects. – Jonathan Leffler Nov 27 '22 at 01:05
  • You also have to worry about overflows — how much space does `word` point at? You've not limited the length of the string read via `scanf()`, so you are vulnerable to buffer overflow. (See: [How to prevent `scanf()` causing a buffer overflow in C?](https://stackoverflow.com/q/1621394/15168)). And you need to know ensure that `words` provides enough space too — but how you do that depends on how `words` is defined. – Jonathan Leffler Nov 27 '22 at 01:08

1 Answers1

2

Assuming word and words are char * then assigning words to word merely means both pointers are pointing to the same bit of memory.

If you wish to treat them as separate strings, you must use a function like strcpy or strncpy, and ensure word points to a separate block of valid memory you can copy into.

E.g.

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

int main(void) {
    char original[100];
    char copy[100];

    if (scanf("%99s", original) == 1) {
        strcpy(copy, original);
    }

    // ...

    return 0;
}
Chris
  • 26,361
  • 5
  • 21
  • 42
  • Would recommend strdup(), which does exactly what is required, if using dynamic allocation. – pmacfarlane Nov 27 '22 at 00:49
  • 1
    I did consider using that, but that's new enough in terms of C standards that I felt it best to go with tried and true. – Chris Nov 27 '22 at 01:07
  • POSIX has defined [`strdup()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/strdup.html) since "forever" (not later than POSIX 1997, possibly earlier, but it wasn't in POSIX.1 1990 or POSIX.2 1992). POSIX defines [`strndup()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/strndup.html) too, but that is more recent (POSIX 2008). The C standard up to and including C17 does not define `strdup()` or `strndup()`; in C23, `strdup()` and `strndup()` will finally be a part of standard C. – Jonathan Leffler Nov 27 '22 at 01:19