include
#include <string.h>
int main()
{
char *array[10]={};
char* token;
token = "testing";
array[0] = "again";
strcat(array[0], token);
}
why it returns Segmentation fault?
I’m a little confused.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Technically, this isn’t valid C. (It is valid C++, though.)
You should use
This declares an array of 10 pointers to char and initializes them all to null pointers.
This declares token as a pointer to char and points it at a string literal which is non-modifiable.
This points the first
charpointer ofarrayat a string literal which (again) is a non-modifiable sequence of char.strcatconcatenates one string onto the end of another string. For it to work the first string must be contained in writeable storage and have enough excess storage to contain the second string at and beyond the first terminating null character (‘\0’) in the first string. Neither of these hold forarray[0]which is pointing directly at the string literal.What you need to do is something like this. (You need to
#include<string.h>and<stdlib.h>.)I’ve gone for runtime calculation of sizes and dynamic allocation of memory as I’m assuming that you are doing a test for where the strings may not be of known size in the future. With the strings known at compile time you can avoid some (or most) of the work at compile time; but then you may as well do
"againtesting"as a single string literal.