What is the difference between a string and a user typed string in C

I use a smaller part of the code to test the functionality for a larger (beginner) program, but I do not understand the difference between the two lines.

I found and used:

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

int main()
{

char *string, *found;

string = strdup ("1/2/3");
printf("Orig: '%s'\n",string);

while ((found = strsep(&string,"/")) != NULL )
  printf ("%s\n",found);

return (0);
}

and it prints the markers one at a time.

Then, when I try to jump to the line entered by the user:

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

int main()
{
  char string[13],
  char *found, *cp = string;

  fprintf(stderr, "\nEnter string: ");
  scanf("%12s",string);
  printf("Original string: '%s'\n",string);

  while((found =  strsep(&cp,"/,-")) != NULL )
    printf("%s\n",found);

  return(0);
}

I get a seg error. I understand the basics of pointers, arrays, and strings, but obviously I'm missing something and would like someone to tell me what it is!

Also - if I change printf("%s\n",found);to printf("%i\n",found);, I get the returned returned integers, but always the right amount, for example. If I enter 1/2/3, I get three lines of integers, 1111/2222I get two lines.

Thank!

-Edit-   strsep, . .

+4
7

string strdup, .

string , scanf, scanf . undefined , .

. :

char string[80];

scanf, :

 scanf("%79s",string);
+4

:

  • string , strdup, .

  • , undefined.

, malloc .

char *string,*found;
string = malloc(100); // Make it large enough for your need.
fprintf(stderr, "\nEnter string: ");
scanf("%99s",string);

char string[100], *found;
fprintf(stderr, "\nEnter string: ");
scanf("%99s",string);

, . .

+2

.

char string[256];

malloc()

char *string;

string = (char*) malloc(256 * sizeof(char));
if (string == NULL)
   {
   //error
   }

free(string);
+1

! . "char string [256]" .

"strdup", malloc, scanf .

, , scanf while, . , insuffisante, .

stdin - , fgets.

0

. string char, . , strdup ("1/2/3"); , char pointer *string strdup . , .

string, , : -

 char *string = malloc(50);// here malloc will allocate 50 bytes from heap
0

, . strdup , , segfault. malloc, scanf.

0

char [13] char cp = string

cp - char 1

char 13 , 13 , -

0

Source: https://habr.com/ru/post/1695116/


All Articles