Reputation: 434
I have an exam next month and I'm playing around with everything that isn't clear to me. I created a function that simply allows the user to input a string and returns the string and its length as parameters. I'm using strcpy to copy the string in the variable declared inside the function into the first parameter parameter but the program crashes when it arrives at that point.
#include <stdio.h>
#include <string.h>
#define MAX 100
void insertString(char orig[], int *len);
int main()
{
int length = 0;
char str[MAX] = {0};
insertString(str[MAX], &length);
printf("You have inserted: %s", str);
printf("The length of the stream you entered is: %d", length);
return 0;
}
void insertString(char orig[], int *len)
{
char str1[MAX];
printf("Insert your string: ");
fgets(str1, MAX, stdin);
strcpy(orig, str1);
*len = strlen(str1) - 1;
}
Upvotes: 1
Views: 673
Reputation: 5239
char str[MAX] = {0};
insertString(str[MAX], &length);
For the matter, when you do char str[MAX]
with MAX
as 100 . It creates an array with subscripts 0
to 99
str[MAX]
does not exist. {Atleast you are not allowed to access it}
insertString(str, &length);
will do good, it passes an array
Upvotes: 1
Reputation: 64
you should either use
insertString(str, &length);
or
insertString(&str[0], &length);
Upvotes: 0
Reputation: 4515
Change the line insertString(str[MAX], &length);
to insertString(str, &length);
The former is trying to pass a character (surprised this didn't give you a warning) and the latter is passing the pointer to the start of the buffer, which is what, I think, you want...
Upvotes: 2
Reputation: 121427
insertString(str[MAX], &length);]
passes a character (that too out of bounds).
You wanted to pass a pointer to the array:
insertString(str, &length);
Upvotes: 4
Reputation: 53386
Change
insertString(str[MAX], &length);
to
insertString(str, &length);
You want to pass array of characters not just one character.
Upvotes: 1