-3

I'm struggling to copy a string within an array at a given index to another array of strings, any suggestions? When trying to print out the value of tempVal at any given index, it doesn't return anything.

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

int main(void) {

   const int NUM_VALS = 20;
   int i;
   int matchCount = 0;

   int actualInput;
   scanf("%d", &actualInput);
   char userString[actualInput][NUM_VALS];
   char tempVal[actualInput][NUM_VALS];

   for (i = 0; i < actualInput; ++i) {
      scanf("%s", userString[i]);
      // printf("%s", userString[i]);
         strncpy(userString[i], tempVal[i], strlen(userString[i])); // < -- Not sure how to make work
         printf("%s", tempVal[i]); // <-- Doesn't output anything?
   }

   return 0;
}
  • 3
    There is almost never a good reason to use [`strncpy`](http://www.cplusplus.com/reference/cstring/strncpy/) read the documentation carefulley. Especially the parte that says: _No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow)._ – Jabberwocky Mar 20 '20 at 08:08
  • [How can code that tries to prevent a buffer overflow end up causing one?](https://devblogs.microsoft.com/oldnewthing/20050107-00/?p=36773) – Maxim Egorushkin Mar 20 '20 at 10:35

3 Answers3

0

use the function which will limit the number of chars read and place the terminatins zero as well

for (int i = 0; i < actualInput; ++i) {
    fgets(userString[i], NUM_VALS, stdin);
    strcpy(tempVal[i], userString[i]); // < -- Not sure how to make work
    printf("%s\n", tempVal[i]); // <-- Doesn't output anything?
}
0___________
  • 60,014
  • 4
  • 34
  • 74
0

It is no wonder why you got no appropriate output because with the provided code you high-probably will get a Segmentation fault. Beside this, there are several issues in the code. To explain them all and also answer the heading question would explode the frame. You can see how I corrected the code in my manner below.

char* strcpy ( char* destination, const char* source )

strcpy is a potential risk for causing buffer overflow if the destination char buffer is not large enough to hold the string to be copied by source. This in your case okay, because each buffers, userString[i] and tempVal[i], have the same capacity (amount of char elements), but if the code changes it could be harmful.

Note that you also should limit the amount of input characters when you catch the string from stdin. For this reason, fgets() is safer than scanf(), since it explicitly requires a maximum amount of characters to read.

char* strncpy ( char* destination, const char* source, size_t num );

strncpy fails to append a terminating null character if the first num characters of the source string do not contain a terminating \0.

Rather use snprintf() which is safe to 1. proofs the size of the destination buffer and limits the amount of characters to read and 2. always appends a null character (assuming the scan process was successful and no errors occurred):

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

int main(void) {

   const int NUM_VALS = 20;
   int i;

   int s_num;
   printf("Enter number of strings in array: ");
   scanf("%d", &s_num);
   getchar();

   char userString[s_num][NUM_VALS];
   char tempVal[s_num][NUM_VALS];

   for (i = 0; i < s_num; ++i) {
   printf("Enter string at userString[%d]: ",i);

   if(fgets(userString[i],NUM_VALS, stdin) == NULL)
   {
       // error handling
       if(ferror(stdin))
       {
            // handle I/O error.
       }
       else if(feof(stdin))
       {
           // end of file is reached.
       }
   }
   else
       userString[i][strcspn(userString[i], "\n")] = 0;

   //printf("%s", userString[i]);
   }

   printf("\n");

   for (i = 0; i < s_num; ++i) {

      if(snprintf(tempVal[i], sizeof(tempVal[i]), "%s", userString[i]) < 0)
      {
        // error handling
        fprintf(stderr,"Encoding error occurred!");
      }
      printf("tempValue[%d]: %s\n", i, tempVal[i]);
   }
   return 0;
}

Output at a test run:

Enter number of strings in array: 3               
Enter string at userString[0]: hello    
Enter string at userString[1]: world 
Enter string at userString[2]: test

tempValue[0]: hello
tempValue[1]: world
tempValue[2]: test
0

Sorry guys,

I am taking a class and new to C. I was able to figure out how to solve my problem. I appreciate the suggestions for fixing the code, unfortunately they are beyond the scope of what I have learned in my intro course. I had to find word frequencies using a string array and for loops. Here is the complete working code:

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

int main(void) {

   const int NUM_VALS = 20;
   int i;
   int j;
   int matchCount = 0;

   int actualInput;
   scanf("%d", &actualInput);

   char userString[actualInput][NUM_VALS];
   char tempVal[actualInput][NUM_VALS];

   for (i = 0; i < actualInput; ++i) {
      scanf("%s", userString[i]);
      strcpy(tempVal[i], userString[i]);
     // printf("%s\n", userString[i]);
     // printf("%s\n", tempVal[i]);
   }

   for (i = 0; i < actualInput; ++i) {
      matchCount = 0;
      for (j = 0; j < actualInput; ++j) {
         if (strcmp(userString[i], tempVal[j]) == 0) {
            matchCount++;
         }
      }
      printf("%s %d\n", userString[i], matchCount);
   }



   return 0;
}