C将每个字符添加到数组中 < C++ >我可以在代码 数组:每个索引中添加每个代码> char > string *x=new string[10]; x[0] += "a"; x[0] += "b"; x[0] += "c"; x[1] += "x"; x[1] += "y"; x[1] += "z"; cout << "x[0]=" << x[0] << endl; // would be "abc" cout << "x[1]=" << x[1] << endl; // would be "xyz"

C将每个字符添加到数组中 < C++ >我可以在代码 数组:每个索引中添加每个代码> char > string *x=new string[10]; x[0] += "a"; x[0] += "b"; x[0] += "c"; x[1] += "x"; x[1] += "y"; x[1] += "z"; cout << "x[0]=" << x[0] << endl; // would be "abc" cout << "x[1]=" << x[1] << endl; // would be "xyz",c,C,如何在C中实现相同的功能 首先实现/发明一个“字符串” 之后,您可以实现该功能。记住正确的错误处理。我刚才使用了abort(),为简洁起见,在普通代码中应该运行析构函数 #include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct string { char *begin; char *end; size_t free; } string; void

如何在C中实现相同的功能

首先实现/发明一个“字符串”

之后,您可以实现该功能。记住正确的错误处理。我刚才使用了
abort()
,为简洁起见,在普通代码中应该运行析构函数

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

typedef struct string {
    char *begin;
    char *end;
    size_t free;
} string;
void string_init(string *t) {
   t->begin = t->end = NULL;
   t->free = 0;
}
void string_fini(string *t) {
   free(t->begin);
}
// iadd convention from python
int string_iadd_cstr(string *t, const char *str) {
   const size_t addlen = strlen(str);
   if (t->free < addlen + 1) {
       const size_t curlen = t->end - t->begin;
       const size_t newlen = curlen + 1 + addlen;
       void *tmp = realloc(t->begin, newlen);
       if (tmp == NULL) {
           return -1;
       }
       t->begin = tmp;
       t->end = t->begin + curlen;
       t->free = newlen - curlen;
   }
   memcpy(t->end, str, addlen + 1);
   t->end += addlen;
   t->free -= addlen;
   return 0;
}
int string_print(string *t) {
    return printf("%s", t->begin);
}

int main() {
    // string *x=new string[10];
    string *x = malloc(10 * sizeof(*x));
    if (x == NULL) abort();
    for (size_t i = 0; i < 10; ++i) {
        string_init(&x[i]);
    }

    if (string_iadd_cstr(&x[0], "a")) abort();
    if (string_iadd_cstr(&x[0], "b")) abort();
    if (string_iadd_cstr(&x[0], "c")) abort();
    if (string_iadd_cstr(&x[1], "x")) abort();
    if (string_iadd_cstr(&x[1], "y")) abort();
    if (string_iadd_cstr(&x[1], "z")) abort();

    // cout << "x[0]=" << x[0] << endl;
    printf("%s", "x[0]=");
    string_print(&x[0]);
    printf("\n");
    fflush(stdout);

    // cout << "x[1]=" << x[1] << endl;
    printf("%s", "x[1]=");
    string_print(&x[1]);
    printf("\n");
    fflush(stdout);

    // run destructors
    for (size_t i = 0; i < 10; ++i) {
        string_fini(&x[i]);
    }
    free(x);
}
#包括
#包括
#包括
typedef结构字符串{
字符*开始;
字符*结束;
大小不限;
}弦;
无效字符串_init(字符串*t){
t->begin=t->end=NULL;
t->free=0;
}
无效字符串_fini(字符串*t){
自由(t->begin);
}
//来自python的iadd约定
int string_iadd_cstr(string*t,const char*str){
const size\u t addlen=strlen(str);
如果(t->freeend-t->begin;
const size\u t newlen=curlen+1+addlen;
void*tmp=realloc(t->begin,newlen);
if(tmp==NULL){
返回-1;
}
t->begin=tmp;
t->end=t->begin+curlen;
t->free=newlen-curlen;
}
memcpy(t->end,str,addlen+1);
t->end+=addlen;
t->free-=addlen;
返回0;
}
int字符串_打印(字符串*t){
返回printf(“%s”,t->begin);
}
int main(){
//字符串*x=新字符串[10];
字符串*x=malloc(10*sizeof(*x));
如果(x==NULL)中止();
对于(尺寸i=0;i<10;++i){
字符串_init(&x[i]);
}
if(string_iadd_cstr(&x[0],“a”))abort();
if(string_iadd_cstr(&x[0],“b”)abort();
if(string_iadd_cstr(&x[0],“c”))abort();
if(string_iadd_cstr(&x[1],“x”))abort();
if(string_iadd_cstr(&x[1],“y”))abort();
if(string_iadd_cstr(&x[1],“z”))abort();

//您的C代码中有几个问题

  • buff是一个空数组,因为您只使用
    buff[0]
  • 变量l似乎从未定义/初始化过,您可以对其进行免费修改
  • buff2[count2]+=buf[i];
    始终修改相同的
    buff2[count2]
    直到换行,因为在这种情况下,您不增加buff2,但仅在读取换行时增加,您确定要这样做吗
  • buff2的结尾不是空字符,这可能解释了当我打印出buff2值时,我总是得到奇怪的值
  • 如果写入buff2产生未定义的行为,则没有保护

可以用C

char ** x = calloc(10, sizeof(char *));
我使用calloc来初始化空指针

以及相当于:

可能是

 strCat(&x[0], "a");
与:

例如:

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

char * const strCat(char ** p, const char * s)
{
   if (s != NULL) {
     if (*p == NULL)
       *p = strdup(s);
     else { 
       size_t len = strlen(*p);

       *p = realloc(*p, len + strlen(s) + 1); /* may be detect realloc returns NULL on error */
       strcpy(*p + len, s);
     }
   }

   return *p;
}

int main()
{
  char ** x = calloc(10, sizeof(char *));

  strCat(&x[0], "a");
  strCat(&x[0], "b");
  strCat(&x[0], "c");
  
  strCat(&x[1], "x");
  strCat(&x[1], "y");
  strCat(&x[1], "z");
  
  printf("x[0]=%s\n", x[0]);
  printf("x[1]=%s\n", x[1]);
  
  free(x[0]);
  free(x[1]);
  free(x);
  
  return 0;
}
在valgrind下运行:


但是请注意,每次连接一个新字符串时,都需要遍历当前字符串以了解其长度,这不是由
std::string
完成的,因为无论采用何种方式,它都知道所使用的长度,因为KamilCuk的答案就是这样的,如果您不想使用
strcat
,这里有一个简单的示例s是一个演示如何连接字符串的最小示例,但诸如内存重新分配之类的事情尚未实现

#include <stdio.h>
#include <stdlib.h>

int main(void) {

    char buf[30] = "LOREM \n IPSUM DOLOR SIT AMET\0";
    char *buff2;
    int i = 0, n = 30;
    buff2 = (char*)malloc(512 * sizeof(char));

    //set first element of buff2 to be terminating null char
    buff2[0] = '\0';
    
    for(i = 0; i < n; i++) {
        if(buf[i] != '\n') {    
            buff2[i + 1] = '\0'; // shift terminating null char forward
            buff2[i] = buf[i];
        } else {
            buff2[i + 1] = '\0'; // shift terminating null char forward
            buff2[i] = 'n';
        }
    }
    
    printf("%s\n",buff2);
    
    return EXIT_SUCCESS;
}
#包括
#包括
内部主(空){
char buf[30]=“LOREM\n IPSUM DOLOR SIT AMET\0”;
char*buff2;
int i=0,n=30;
buff2=(char*)malloc(512*sizeof(char));
//将buff2的第一个元素设置为终止空字符
buff2[0]='\0';
对于(i=0;i

它将换行符替换为“n”字符;您可以根据需要进行更改。当然,您只需注意处理实际分配的元素。不包括从文件中读取的函数,因为我们没有该文件;这很容易实现。我建议您研究
fgetc

将a和b作为
std::string
等价项
a+=b的nt;
在C中可以是
strcat(a,b)在C++中使用LIB,为什么不在C中使用LIB?如果需要,可以使用<代码> ReLoCu增加结果字符串长度。首先,这是什么:<代码> L++<代码>?这是L,而不是I。而且,似乎你在数组中添加了char值。uff2[count2]+=buf[i];
为建议的每个位置创建一个指针数组,使用
realloc
strcat(a,b)
然后可以使用
%s
读取(fd,buf,sizeof(buf[g])打印指针。
在最好的情况下,只将一个字符读入
buf[0]
,什么interrest的数组为255?警告@mohitharma
使用%s打印指针是错误的,该格式写入了一个(假定的)数组的内容String,使用%P为PoTrSnCo奇怪的是,你的答案不是UV,对于非C++用户来说太复杂了,所以,我要做的是,-)两个评论:海报需要添加一个<代码> char <代码>到一个字符串,即使他的<代码> C++ +/Cuth>示例正在添加一个字符串。通常不需要分配比你需要的更多的空间,只需在每个追加上执行一个<代码> RealCalc>代码>。在极端情况下(tyny增量/巨大缓冲区)进行预分配时,您可能会获得最大10倍的加速。除非您不是在一个紧密的循环中使用字符串,否则这不值得额外的复杂性。您忘记了realloc
buff2
所指的内容。海报正在进行512字节的多次读取,这一事实暗示他希望能够以更多的字节结束512字节。“当然,您只需要小心处理实际已分配的元素。”这是一个最小的示例。我的答案也不包括filestream。OP想知道如何连接字符串-这是对该问题的回答。
 strCat(&x[0], "a");
char * const strCat(char ** p, const char * s)
{
   if (s != NULL) {
     if (*p == NULL)
       *p = strdup(s);
     else { 
       size_t len = strlen(*p);

       *p = realloc(*p, len + strlen(s) + 1); /* may be detect realloc returns NULL on error */
       strcpy(*p + len, s);
     }
   }

   return *p;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * const strCat(char ** p, const char * s)
{
   if (s != NULL) {
     if (*p == NULL)
       *p = strdup(s);
     else { 
       size_t len = strlen(*p);

       *p = realloc(*p, len + strlen(s) + 1); /* may be detect realloc returns NULL on error */
       strcpy(*p + len, s);
     }
   }

   return *p;
}

int main()
{
  char ** x = calloc(10, sizeof(char *));

  strCat(&x[0], "a");
  strCat(&x[0], "b");
  strCat(&x[0], "c");
  
  strCat(&x[1], "x");
  strCat(&x[1], "y");
  strCat(&x[1], "z");
  
  printf("x[0]=%s\n", x[0]);
  printf("x[1]=%s\n", x[1]);
  
  free(x[0]);
  free(x[1]);
  free(x);
  
  return 0;
}
% gcc -Wall a.c
% ./a.out
x[0]=abc
x[1]=xyz
%
% valgrind ./a.out
==113490== Memcheck, a memory error detector
==113490== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==113490== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==113490== Command: ./a.out
==113490== 
x[0]=abc
x[1]=xyz
==113490== 
==113490== HEAP SUMMARY:
==113490==     in use at exit: 0 bytes in 0 blocks
==113490==   total heap usage: 7 allocs, 7 frees, 98 bytes allocated
==113490== 
==113490== All heap blocks were freed -- no leaks are possible
==113490== 
==113490== For counts of detected and suppressed errors, rerun with: -v
==113490== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
%
#include <stdio.h>
#include <stdlib.h>

int main(void) {

    char buf[30] = "LOREM \n IPSUM DOLOR SIT AMET\0";
    char *buff2;
    int i = 0, n = 30;
    buff2 = (char*)malloc(512 * sizeof(char));

    //set first element of buff2 to be terminating null char
    buff2[0] = '\0';
    
    for(i = 0; i < n; i++) {
        if(buf[i] != '\n') {    
            buff2[i + 1] = '\0'; // shift terminating null char forward
            buff2[i] = buf[i];
        } else {
            buff2[i + 1] = '\0'; // shift terminating null char forward
            buff2[i] = 'n';
        }
    }
    
    printf("%s\n",buff2);
    
    return EXIT_SUCCESS;
}