【发布时间】:2019-05-06 16:38:20
【问题描述】:
我正在处理有关使用动态内存分配修改字符串的问题。我的代码的适用部分如下:
./dma 5
#include <stdio.h>
#include <stdlib.h>
char* strcopy(char* destination, char* source);
char *strconcat(char* destination, char* source);
int main(int argc, char *argv[]) {
int cmd, a=1, b, length_of_str, n, n2;
char* pstring[atoi(argv[1])];
for (b=0; b<atoi(argv[1]); b++) {
printf("Enter the length of string %d: ", b+1);
scanf("%d", &length_of_str);
pstring[b]=(char *)malloc(length_of_str*sizeof(char));
printf("Please enter string %d: ", b+1);
scanf("%s", &pstring[b]);
}
while (a!=0) {
printf("Your strings are: \n");
for (b=0; b<atoi(argv[1]); b++) {
printf("String number %d - \"%s\"\n", b+1, &pstring[b]);
}
printf("Options:\n");
printf("1 - Find string length\n");
printf("2 - Compare strings\n");
printf("3 - Copy strings\n");
printf("4 - Concatenate strings\n");
printf("5 - Quit\n");
printf("Please enter your option: ");
scanf("%d", &cmd);
switch (cmd) {
case 3:
printf("Enter the number of the source string: ");
scanf("%d", &n);
printf("Enter the number of the destination string: ");
scanf("%d", &n2);
strcopy(pstring[n-1], pstring[n2-1]);
break;
case 4:
printf("Enter the number of the source string: ");
scanf("%d", &n);
printf("Enter the number of the destination string: ");
scanf("%d", &n2);
strconcat(pstring[n-1], pstring[n2-1]);
break;
case 5:
a=0;
break;
default:
printf("Invalid Option.\n");
break;
}
}
free(pstring);
return 0;
}
char* strcopy(char* destination, char* source) {
destination=(char *)realloc(*source, sizeof(char)*strlength(destination));
for (; *source!='\0'; source++) {
*destination=*source;
destination++;
}
*destination='\0';
return destination;
}
char* strconcat(char* destination, char* source) {
destination=(char *)realloc(*source, sizeof(char)*strlength(destination));
for (; *destination!='\0'; destination++) {
}
for (; *source!='\0'; source++) {
*destination=*source;
destination++;
}
*destination='\0';
return destination;
}
我需要将 realloc 合并到我的连接和复制函数中(这应该没问题,因为它们在单独的问题中工作)。我尝试了多种方法,也尝试了不同的语法,但我似乎只遇到分段错误或无效指针。我究竟应该如何合并 realloc?预期结果应如下所示:
Your strings are:
String number 1 – “first”
String number 2 – “second”
String number 3 – “third”
String number 4 – “fourth”
String number 5 – “fifth”
Options:
1 – Find string length
2 – Compare strings
3 – Copy strings
4 – Concatenate strings
5 – Quit
Please enter your option: 3
Enter the number of the source string: 2
Enter the number of the destination string: 5
Your strings are:
String number 1 – “first”
String number 2 – “second”
String number 3 – “third”
String number 4 – “fourth”
String number 5 – “second”
Options:
1 – Find string length
2 – Compare strings
3 – Copy strings
4 – Concatenate strings
5 – Quit
Please enter your option:
【问题讨论】:
-
这些函数返回一个字符串,但您对该函数的调用不会存储返回的字符串。此外,您在 strconcat 中的 realloc 似乎使源字符串成为目标字符串的大小,而不是两个字符串的大小。
-
更不用说如果
atoi(argv[1])失败了。atoi提供零错误报告。请改用strtol并在创建指针的 VLA 之前验证转换。
标签: c string pointers dynamic-memory-allocation