【发布时间】:2020-03-05 18:02:40
【问题描述】:
我正在尝试在 Linux (Ubuntu 18.04) 上的 C 中将 char 数组的元素向右移动,并尝试为此创建一个函数。我基本上想将x 数量的元素添加到数组的开头,并将其余数据移动x(向右)。如果新元素 + 旧有效元素超过 char 大小,我希望函数返回错误并且不进行任何移位。我还创建了一个指向char 数组的char 指针,并使用结构来设置char 数据。
这是我做的一个测试程序:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
struct struct1
{
char str[10];
int myNum;
};
struct struct2
{
char str[5];
};
int shiftChar(char *arr, int size, int length)
{
for (int i = 0; i < length; i++)
{
// I know I am calculating this incorrectly. Though, not sure how I should go about checking if the new size will exceed the length of the char array.
if (length < ((i + 1) + size))
{
return -1;
}
// If element is 0, we shouldn't shift it (usually represents garbage value?). Not sure how to detect whether an element of a char array was filled with actual data or not.
if (arr[i] == 0)
{
continue;
}
arr[i + size] = arr[i];
fprintf(stdout, "Replacing %c with %c at %d => %d\n\n", arr[i + size], arr[i], i, i + size);
}
for (int i = 0; i < size; i++)
{
arr[i] = 0;
}
return 0;
}
int main()
{
char buffer[256];
struct struct1 *struct1 = (struct struct1 *) (buffer);
struct struct2 *struct2 = (struct struct2 *) (buffer + sizeof(struct struct1));
struct1->myNum = 5;
strncpy(struct1->str, "Hello!", 6);
strncpy(struct2->str, "TST", 3);
fprintf(stdout, "Buffer => ");
for (int i = 0; i < (sizeof (struct struct1) + sizeof(struct struct2)); i++)
{
fprintf(stdout, "%c", buffer[i]);
}
fprintf(stdout, "\n\n");
if (shiftChar(buffer, 6, 256) != 0)
{
fprintf(stdout, "Error shifting char array.\n");
//exit(1);
}
struct1 = (struct struct1 *) (buffer + 6);
struct2 = (struct struct2 *) (buffer + sizeof(struct struct1) + 6);
fprintf(stdout, "struct1->str => %s\n", struct1->str);
exit(0);
}
这是一个示例输出:
...
Error shifting char array.
struct1->str => Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hell`����
我知道我做错了,但我不确定我做错了什么,或者我是否应该采取不同的方式。
我的主要问题是:
shiftChar()函数我做错了什么?有没有更好/更简单的方法来实现我想要做的事情?
有没有办法检查
char数组中的元素是否有垃圾值(例如尚未填充的值)?我想我可以使用memset()之类的东西将缓冲区设置为所有0,但是如果我有一个int指向值为'0' 的缓冲区数据的结构会发生什么。如果我检查值是否等于“0”,我想这将被排除在移位之外。
我也对此进行了研究,但我遇到的大多数线程都是针对 C++ 或向左移动元素。我无法为我的问题找到可靠的解决方案。我将在我正在制作的另一个程序中使用该解决方案(如果有的话),我需要在开头将struct iphdr 的大小添加到现有缓冲区字符(数据已经通过struct iphdr 和@ 填充) 987654337@) 这样我就可以创建和发送 IPIP 数据包(网络编程)。我也知道我可以制作一个全新的 char 并从旧缓冲区复制数据(同时保持第一个 sizeof(struct iphdr) 元素免费),但我想这会对我的情况造成相当大的影响,因为我每秒将不得不这样做数千次,最好只修改现有缓冲区char。
我是 C 编程新手。因此,我确定我缺少一些东西。
如果您需要任何其他信息,请告诉我,我们非常感谢您的帮助!
感谢您的宝贵时间。
【问题讨论】:
-
只要数组足够大以适应大小的增加,
memmove()是移动字节的最佳方式。 -
@LeeDanielCrocker 谢谢!我制作了一个函数,我很快就会发布它,它使用
memmove()和memcpy()。