-1

I am trying to write an argument to a string. What am I doing wrong? How would it be more correct to write the argument from getopt to a string?

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

int main(int argc, char *argv[])
{
    char fsrt[100], sstr[100], tstr[100];
    int rez = 0;
    while ( (rez = getopt(argc, argv, "f:s:l:")) != -1 )
    {
        if (rez == 'f') {
                strcat(fsrt, optarg);
        }
        if (rez == 's') {
                strcat(sstr, optarg);
        }
        if (rez == 'l') {
                strcat(tstr, optarg);
        }
    }


    printf("%s %s %s", fsrt, sstr, tstr);

    return 0;
}

Update: strange symbol in output.

./test -f one -s two -l three
output: https://i.stack.imgur.com/kksVh.png
Tympa
  • 3
  • 2
  • 2
    Initialize, Initialize, Initialize. – Sourav Ghosh Dec 14 '22 at 13:49
  • 1
    State the input you're providing to your program via the command line, the output you expected to get, and the output you are actually receiving, in your post above. Include any error messages you are receiving. – Robert Harvey Dec 14 '22 at 13:49
  • You cannot use a function meant for string concatenation on things that are not (yet) strings. – Lundin Dec 14 '22 at 14:38

1 Answers1

1
char fsrt[100] = "", sstr[100]= "", tstr[100]= "";

If you don't initialize the char arrays they randomly point somewhere in memory.

The incredible Jan
  • 741
  • 10
  • 17
  • 1
    Or by doing `char fsrt[100] = { '\0' },....` or `memset(fsrt, '\0', sizeof(fsrt));`. – Flewz Dec 14 '22 at 14:00
  • 1
    or by using `strcpy()` instead of `strcat)`- The example doesn't show any reason why `strcat()` is used. The answer could be improved if it made clear that `strcat()` is intended to add something to an existing string rather than "write an argument to a string" as in the title of the question – Ingo Leonhardt Dec 14 '22 at 14:03
  • @IngoLeonhardt `strncpy()` – dimich Dec 14 '22 at 14:17
  • The formulation "randomly point" is incorrect. An array does not "point" anywhere. An array is not a pointer, even if it [decays](https://stackoverflow.com/q/1461432/12149471) to a pointer in many situations. Even when an uninitialized array with indeterminate (i.e. random) values decays to a pointer, the value of this pointer will not have an indeterminate value, so it will not "randomly point" anywhere. Instead, the decayed pointer will point to the first element of the uninitialized array. – Andreas Wenzel Dec 14 '22 at 14:24