gpt4 book ai didi

c - strlen 指针与数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:02 25 4
gpt4 key购买 nike

我在使用指针与静态数组时遇到了一些问题。我陷入了这个错误:

void LZWCompress(FILE* file, char minCodeSize, char *pixels, int area)
{

int k = ++minCodeSize, i, len = DEFAULT, jump = 0, dicLen;
lzwDict *dictionary = NULL, *s, *temp;

char *curr, next[2], *buffer;

dicLen = initializeDictionary(&dictionary, minCodeSize);
for(i = 0; i < area; i++)
{
if(dicLen + 1 >= pow(2, k))
k = k + 1;

curr = (char*) malloc(sizeof(char) * DEFAULT);
curr[0] = pixels[i];
curr[1] = '\0';

printf("strlen %lu %s\n", strlen(curr)); ### strlen(curr) = 0 ? WH ? ###
if((i + 1) > area)
{
//outputs curr
break;
}


len = len + 1;
jump = jump + 1;

next[0] = pixels[i + jump];
next[1] = '\0';

buffer = (char*) malloc(sizeof(char) * len);
printf("%lu %lu %lu \n", strlen(buffer), strlen(curr), strlen(next)); ### prints out "0 0 1" ###

(...) 代码继续,由于这个问题我得到了 Abort Trap

    buffer = strcat(curr, next);
HASH_FIND_STR(dictionary, buffer, s);

if(s)
{
printf("YOLO\n");
do{
jump = jump + 1;

if(i + jump >= area)
exit(-1);

printf("%d \n", len);
curr = (char*) realloc(curr, sizeof(char) * len); ### Here i get Abort Trap 6 ###

(...) 代码继续

为什么我使用数组 (next[2]) 而不是使用指针 (*curr, *buffer) 时得到预期的结果。

如果相关的话,我正在使用 OSX Yosemite。

最佳答案

根据strlen doc :

The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).

This should not be confused with the size of the array that holds the string.

如果 pixels[i] 等于 0,则 strlen(next) 将为 0。

关于c - strlen 指针与数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26990222/

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