gpt4 book ai didi

在 c 中将字符串分成 512 字节的 block

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:58 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,它接受一个字符串并将其分割成 512 字节的 block 。它获取字符串中的前 512 个字节,并将其存储在 chopped[0] 中,然后将接下来的 512 个字节存储在 chopped[1] 中......等等。当我在函数中打印出 chopped 时,它似乎在工作,但是当我返回 chopped[0] 时,它会给我整个字符串,而不仅仅是第一个 512。有什么想法吗?

char** chopString(){
char string[]="1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200";

int len=strlen(string)+1;
int i,j,bytes,blocks;
int blockSize=512;
bytes=len*sizeof(char);
blocks=(int)ceil((double)bytes/blockSize); //determine number of blocks rounded up

char* chunk=malloc(blockSize+1);
char* newChunk=malloc(blockSize+1);
char** chopped=malloc(sizeof(char*)*(blocks+1)); //blockSize+1 for null character


for(j=0; j<blocks; j++){
len=strlen(string)+1; //get length of string
if(len<blockSize){ //if the string can fit in one block
bytes=len; //the number of bytes to write is the length
}else{ //if it doesn't fit in one block
bytes=blockSize; //then bytes to write is one block
}
strcpy(chunk,string); //copy newString into chunk
newChunk=chunk; //keep pointer to begining of chunk

for(i=0; i<bytes; i++){
chunk++;
}
strcpy(string,chunk); //set new string to remaining portion
*chunk='\0'; //set end of chunk to null
chopped[j]=newChunk; //put chunk into array
printf("Chopped[%d]: %s\n",j,chopped[j]);
printf("length: %d",(int)strlen(chopped[j]));
}
chopped[j]=NULL;
printf("\n");
return chopped;
}

最佳答案

strcpy 复制整个字符串。试试 strncpy。请注意,您需要在字符串末尾添加一个空终止符。

http://www.cplusplus.com/reference/cstring/strncpy/

关于在 c 中将字符串分成 512 字节的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29907093/

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