next()的PHP函數,我試圖實現C. next() PHP函數,如果我有如何實現用C
我實現不同的是我想要做更多的一個點,這個工作。例如:
,如果我有兩個char *
,如:
char * a = "ac\0";
char * b = "bd\0";
我打電話:
printf("%c", cgetnext(a));
printf("%c", cgetnext(b));
printf("%c", cgetnext(a));
printf("%c", cgetnext(b));
得到類似的輸出:abcd
,但我得到abab
這裏是我的代碼:
`#include <string.h>
#include <stdlib.h>
typedef struct
{
int pLocation;
int myindex;
int lastIndex;
} POINTERINFORMATION;
int __myIndex = 0;
int pointersLocationsLength = 0;
char * temparr = NULL;
POINTERINFORMATION pointersLocations[256];
int
plAdd (int p)
{
if (pointersLocationsLength >= sizeof(pointersLocations)) {
return -1;
} else {
pointersLocations[pointersLocationsLength].pLocation = p;
pointersLocations[pointersLocationsLength].lastIndex = 0;
pointersLocationsLength ++;
return pointersLocationsLength;
}
}
int
getPointer (int p, POINTERINFORMATION * out)
{
int i;
for (i = 0; i < pointersLocationsLength; i++)
{
if(pointersLocations[pointersLocationsLength].pLocation == p)
{
pointersLocations[i].myindex = i;
*out = pointersLocations[i];
return 1;
}
}
return 0;
}
void
getPointerIndex(char ** variable, int * val)
{
char * buf = malloc(256);
if(sprintf(buf,"%p", &variable) > 0){
*val = strtol(buf, NULL, 16);
} else {
*val = -1;
}
}
int
inArrayOfPointers (int pointer)
{
POINTERINFORMATION pi;
return getPointer(pointer, &pi);
}
char
cgetnext(char * arr)
{
char * myarr;
const size_t size = sizeof(char *) + 1;
int pof;
myarr = malloc(size);
getPointerIndex (&arr, &pof);
if (inArrayOfPointers(pof)){
POINTERINFORMATION pi;
if (getPointer(pof, &pi))
{
myarr = (char *)*(int *)pi.pLocation;
__myIndex = pi.lastIndex;
++pointersLocations[pi.myindex].myindex;
} else {
return 0;
}
} else {
if (plAdd(pof) == -1) {
printf(" CANNOT ADD ELEMENT TO ARRAY\n");
exit(0);
} else {
myarr = arr;
__myIndex = 0;
}
}
if (strlen(myarr) == __myIndex) {
return 0;
} else {
temparr = malloc(size);
temparr = strdup(myarr);
return myarr[__myIndex];
}
}`
如何解決這個問題?不同的解決方案解決它是非常折衷的!提前致謝。
對於編隊感到抱歉!我不能在這裏修復。 – Jack 2012-03-09 00:10:22
如果僅顯示相關代碼並更好地描述php的「next」如何工作(它是否會影響數組本身(如果指向同一數組的多個指針都提前?),您將得到更好的答案)。 – 2012-03-09 00:26:14
只是一個說明:你不需要像'char * a =「ac \ 0」那樣手動終止C中的字符串文字;'這可以寫'char * a =「ac」;'編譯器會自動執行此操作,表明您添加了不必要的代碼(可能會令其他人感到困惑)並浪費空間。 – ldrumm 2013-05-11 15:41:39