【发布时间】:2019-02-18 15:51:38
【问题描述】:
我在尝试在 C 中操作 2d 动态数组时遇到问题。我想做的是在 2d 数组的每一行中存储一个 char 字符串,然后执行检查以查看该字符串是否包含某个字符,如果是这样删除所有出现然后转移到空位置。实际发生的是我收到了exit status 1。
有关问题的更多信息,例如,如果我有
Enter string 1: testing
Enter string 2: apple
Enter string 3: banana
我希望输出变成
What letter? a // ask what character to search for and remove all occurences
testing
pple
bnn
这是我的完整代码:
#include <stdio.h>
#include <stdlib.h>
void removeOccurences2(char** letters, int strs, int size, char letter){
// Get size of array
// Shift amount says how many of the letter that we have removed so far.
int shiftAmt = 0;
// Shift array says how much we should shift each element at the end
int shiftArray[strs][size];
// The first loop to remove letters and put things the shift amount in the array
int i,j;
for(i=0;i < strs; i++){
for(j = 0; j < size - 1; j++) {
if (letters[i][j] == '\0'){
break;
}
else {
// If the letter matches
if(letter == letters[i][j]){
// Set to null terminator
letters[i][j] = '\0';
// Increase Shift amount
shiftAmt++;
// Set shift amount for this position to be 0
shiftArray[i][j] = 0;
}else{
// Set the shift amount for this letter to be equal to the current shift amount
shiftArray[i][j] = shiftAmt;
}
}
}
}
// Loop back through and shift each index the required amount
for(i = 0; i < strs; i++){
for(j = 0; j < size - 1; j++) {
// If the shift amount for this index is 0 don't do anything
if(shiftArray[i][j] == 0) continue;
// Otherwise swap
letters[i][j - shiftArray[i][j]] = letters[i][j];
letters[i][j] = '\0';
}
//now print the new string
printf("%s", letters[i]);
}
return;
}
int main() {
int strs;
char** array2;
int size;
int cnt;
int c;
char letter;
printf("How many strings do you want to enter?\n");
scanf("%d", &strs);
printf("What is the max size of the strings?\n");
scanf("%d", &size);
array2 = malloc(sizeof(char*)*strs);
cnt = 0;
while (cnt < strs) {
c = 0;
printf("Enter string %d:\n", cnt + 1);
array2[cnt] = malloc(sizeof(char)*size);
scanf("%s", array2[cnt]);
cnt += 1;
}
printf("What letter?\n");
scanf(" %c", &letter);
removeOccurences2(array2,strs,size,letter);
}
提前致谢!
【问题讨论】:
-
从字符串中删除字母的正确方法是在字符串上保留 2 个索引:一个读取索引,每一步递增 1,一个写入索引,仅当字母增加时才递增与要删除的字母不匹配。更简单意味着更强大。
-
OT:关于诸如
array2[cnt] = malloc(sizeof(char)*size);1) 表达式:sizeof(char)在 C 标准中定义为 1。乘以 1 无效。建议在调用任何堆分配函数时删除表示2):malloccallocrealloc,始终检查(!= NULL)返回值以确保操作成功。如果不成功,则调用perror()输出您的错误消息和系统认为发生错误的文本原因。 -
OT:当调用任何
scanf()系列函数时; 1) 始终检查返回值(不是参数值)以确保操作成功(在这种情况下,如果返回值不等于 1,则函数失败。) 2) 使用输入格式说明符时 '%s ' 和/或 '%[...]' 总是包含一个最大字符修饰符,它比输入缓冲区的长度小 1,因为这些说明符总是附加一个 NU1 字节。这也避免了缓冲区溢出和由此产生的未定义行为的任何可能性 -
OT:为什么这两个声明:
c = 0;和int c;?它们对发布的代码没有任何作用,并且会导致编译器输出一条关于变量被设置但未使用的消息 -
OT:为了便于阅读和理解:1) 请始终缩进代码。在每个左大括号“{”后缩进。在每个右大括号 '}' 之前取消缩进。建议每个缩进级别为 4 个空格 2) 请遵循公理:每行只有一个语句,并且(最多)每个语句一个变量声明。
标签: c arrays memory-management