strcat的问题的char *一个[10] [英] strcat problem with char *a[10]

查看:184
本文介绍了strcat的问题的char *一个[10]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

int main()
{
        char *array[10]={};
        char* token;
        token = "testing";
        array[0] = "again";
        strcat(array[0], token);
}

为什么它返回段错误?

why it returns Segmentation fault?

我有点糊涂了。

推荐答案

从技术上讲,这不是正确的C.(它是合法的C ++,虽然。)

Technically, this isn't valid C. (It is valid C++, though.)

char *array[10]={};

您应该使用

char *array[10] = {0};

本声明的10指针的数组为char和他们都初始化为空指针。

This declares an array of 10 pointers to char and initializes them all to null pointers.

char* token;
token = "testing";

此声明令牌作为一个字符指针和一个字符串文字是不可修改的分吧。

This declares token as a pointer to char and points it at a string literal which is non-modifiable.

array[0] = "again";

这点第一个字符 阵列的指针指向一个字符串字面量这(再次)是不可修改字符序列。

This points the first char pointer of array at a string literal which (again) is a non-modifiable sequence of char.

strcat(array[0], token);

strcat的并置一根弦到另一个字符串的结尾。为它工作的第一个字符串必须包含在可写的存储器,并有足够的额外存储到包含并超越第一个字符串中的第一个空字符('\\ 0')的第二个字符串。这些都不持有数组[0] 这是直接在字符串字面指向

strcat concatenates 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 for array[0] which is pointing directly at the string literal.

什么你需要做的就是这样的事情。 (您需要的#include &LT;文件string.h&GT; &LT; stdlib.h中&GT ;

What you need to do is something like this. (You need to #include <string.h> and <stdlib.h>.)

我已经走了规模的计算运行时间和我假设你正在做的,其中在今后的字符串可能不知道大小的测试动态分配的内存。随着在编译时已知的弦就可以避免在编译时工作的一些(或大部分);但你不妨做againtesting作为一个单一的字符串。

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.

char* token = "testing";
char* other_token = "again";

/* Include extra space for string terminator */
size_t required_length = strlen(token) + strlen(other_token) + 1;

/* Dynamically allocated a big enough buffer */
array[0] = malloc( required_length );
strcpy( array[0], other_token );
strcat( array[0], token );

/* More code... */

/* Free allocated buffer */
free( array[0] );

这篇关于strcat的问题的char *一个[10]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆