[英]strlen returning wrong value
I'm building a text editor using doubly linked lists. 我正在使用双向链表创建文本编辑器。 These are my structs:
这些是我的结构:
#define N 4
typedef struct node
{
char data[N];
int size;
struct node* next;
struct node* prev;
}node;
typedef struct text
{
struct node* head;
struct node* tail;
int count;
int size;
}text;
This is the piece of code that I use to fill the first node. 这是我用来填充第一个节点的代码段。
void push_text (text * t, char * s)
{
int i;
int len = strlen(s);
node *newnode, *nextnode, *head;
newnode = create_node();
t->count++;
head = newnode;
for (i=0; i<len; i++)
{
if (newnode->size < 4)
{
newnode->data[newnode->size] = s[i];
newnode->size++;
}
.
.
.
When I print the node through printf or through the debugger the output is 4 chars long, as expected. 当我通过printf或通过调试器打印节点时,输出为4个字符长,正如预期的那样。 Note that, I print it as soon as the first node is filled so the problem lies in this piece of code.
请注意,我会在第一个节点填满后立即打印,因此问题在于这段代码。 However, when I use
strlen(newnode->data)
I get an output of 5. This is causing me many problems later on. 但是,当我使用
strlen(newnode->data)
我得到的输出为5.这导致我以后遇到很多问题。
What's wrong here? 这有什么不对?
You are not copying the nul
terminator, ac string needs a '\\0'
at the end, so if it has 4 characters it uses 5 bytes, the last one being '\\0'
which is not copied in your loop. 你没有复制
nul
终结符,ac字符串最后需要'\\0'
,所以如果它有4个字符则使用5个字节,最后一个是'\\0'
,它不会在你的循环中复制。
You should however use strcpy()
instead of copying they bytes one by one in a loop. 但是,您应该使用
strcpy()
而不是在循环中逐个复制它们的字节。
The strlen()
function scans the bytes until it finds the '\\0'
, so the missing '\\0'
is causing the Wrong Value !, also that's a reason not to call strlen()
in a loop, which is a very common mistake. strlen()
函数扫描字节,直到它找到'\\0'
,所以缺少'\\0'
导致错误的值 !,这也是不在循环中调用strlen()
的原因,这是一个非常常见的错误。
You cannot put a four-character C string into a four-element array of char
, because you need space for null terminator. 您不能将四个字符的C字符串放入
char
的四元素数组中,因为您需要空终止符。 Change all declarations of data
to 将所有
data
声明更改为
char data[N+1];
You should also use N
in place of constant 4
in expressions that expect the length to be less than N
(eg newnode->size < N
instead of newnode->size < 4
). 您还应该在期望长度小于
N
表达式中使用N
代替常量4
(例如, newnode->size < N
而不是newnode->size < 4
)。
All the answers explained before were correct but no one explain the mistake. 之前解释的所有答案都是正确的,但没有人解释错误。
With an example you will see better the mistake 举个例子,你会看到更好的错误
node.data[0] = 'a';
node.data[1] = 'b';
node.data[2] = 'c';
node.data[3] = 'd';
node.datasize = 4;
In a little endian machine the memory will be filled in that way: 在一个小端机器中,内存将以这种方式填充:
Hex value of 'a', 'b', 'c','d' coded in a byte and four bytes to code the int 'a','b','c','d'的十六进制值以字节编码,四个字节编码为int
Memory: 'a''b''c''d'4000 记忆:'a''b''c''d'000
Then you will obtain... 然后你会得到......
strlen(node.data) --> 5
printf(node.data) --> abcd (plus 4 ascii code).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.