Search code examples
carraysloopsstrcpy

Copy a single character from a character array to another character array in C


I am fairly new to C programming and trying to improve. I have seen a few question similar to this and tried to implement their suggestions using strncpy but it still won't work. Can anyone give me a pointer in the right direction? Thanks.

The aim of the code is to be given a string and split it on finding a blank space. I am deliberately not using strtok().

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

char str[10] ;
char word[10] ;
int i, j, k, l ;

  int main()
{
  printf("Please enter a string of ten characters and I'll find the blanks\n") ;
  fgets(str,10,stdin) ;

  printf("Original string is %s\n", str) ;

  j = 0 ;

  for(i == 0 ; i < 10 ; i++){
    if(!isblank(str[i])){
      strncpy(word[j], &str[i], 1) ;
      printf("i = %d, j = %d, str[i] = %c, word[j] = %c\n",i, j, str[i], word[j]) ;
      j++ ;
    }else{
      printf("%s\n",word) ;
      j = 0 ;
    }
  }
  return 0 ;
}

Solution

  • The problem, as I see it, is in

    for(i == 0 ; i < 10 ; i++)
          ^^
    

    You should be using the assignment (=), like

    for(i = 0 ; i < 10 ; i++)
    

    to set the initial value of i. Otherwise, by accessing the value of an uninitialized local variable (whose value is indeterminate without an initialization), your code will invoke undefined behavior.

    Then, the usage of strncpy() also looks wrong, you're not passing a char *, as required for the first argument.

    Now, that said, two more things,

    1. To copy a single char one at a time, you can simply use the assignment , like

      word[j] = str[i];
      
    2. You should only loop over the input array till the valid entries, not the whole size (10). In case, the input is smaller, you'll again hit UB.