gpt4 book ai didi

c - 根据用户输入构建字符串数组

转载 作者:行者123 更新时间:2023-11-30 19:15:28 24 4
gpt4 key购买 nike

我有以下简单的程序,它将从终端获取用户字符串输入(“”),并将输入逐个字符地解析为字符串数组(称为数组)。每当遇到数字字符时,都会创建一个新字符串:即 ./programname "Hello1 my name is 2john" 将输出为:

Hello

1 my name is

2john

因此,我正在检查输入的每个字符,然后决定是否将其strcatarray[j]处的当前字符串或分配另一个字符串 array[j+1] 并将其附加到该数组的开头。

代码如下:

/*concatenates ts[i] and array[j]*/
char *add_to(char * copy, char ** array, int i , int j,int current_size){
/* expand size of string at array[j]*/
array[j] = realloc(array[j],sizeof(char)*(current_size+2));
/*concate next character of ts*/
char * target = malloc(sizeof(char)*2);
strncpy(target,copy+i,1);
target=strcat(target,"\0");
array[j]=strcat(array[j],target);
return array[j];

}

int main(int argc, char** argv){

/*will hold literals*/
char ** array = malloc(sizeof(char*)*1);
/* current size */
int array_size =1 ;
/* terminal input */
char * ts = *(argv+1);

/* index of array */
int j =0;
/* index of terminal input */
int i =0;
/*current place to concatenate to in array[j] */
int current_size=0;
/* while there is more input */
while(i<strlen(ts)){
/* if we need more space */
if(j==array_size){
printf("%s\n","Expand");
array_size++;
/* assign old pointer to new pointer */
array=realloc(array,array_size*sizeof(char*));
}
/* concatenate array[j] and character at ts[i]*/
array[j]=add_to(ts,array,i,j,current_size);
/*new spot to concatenate when loop around */
current_size++;
/* move onto next character of ts */
i++;
/*if this new character is a digit move to next slot of array */
if(i<strlen(ts)&&isdigit(*(ts+i))!=0){
j++;
current_size=0;
}
}
/* print all literals in array */
j=0;
while(j<array_size){
printf("%s\n",array[j]);
j++;
}
return 0;
}

但是,当输入太大时,程序开始打印多字节字符以及正确的字符串:(Ð-�3))或者更大的结果会导致段错误。

知道我动态分配内存时做错了什么吗?

最佳答案

减少并修复您的代码:

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

char *add_to(char * copy, char ** array, int i , int j, int current_size){//i: start position, j: length of parts
char *target = malloc(j + 1);//+1 for NUL
strncpy(target, copy + i, j);
target[j] = '\0';
return array[current_size-1] = target;
}

int main(int argc, char** argv){
const char *digits = "0123456789";
char **array = NULL;
int array_size = 0;//current size
char *ts = argv[1];//terminal input

int i, j;

for(i = 0; ts[i] != '\0'; i += j){//i: index of the string
//no need size check when expand one by one
array = realloc(array, ++array_size * sizeof(char*));//fail check omitted
j = strspn(ts + i, digits);//The length containing digit
j += strcspn(ts + i + j, digits);//add length containing no digit
add_to(ts, array, i, j, array_size);
}
/* print all string in array */
for(j=0; j<array_size; j++){
puts(array[j]);
}
//deallocate
return 0;
}

关于c - 根据用户输入构建字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32554311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com