在第77行v-> size爲0,而在第186行v-size爲2.我不明白爲什麼這是因爲行186在void _setCapacityDynArr(struct DynArr * v,int newCap)的函數定義的最後(第140行),第77行在調用該函數之後。不知何故,在函數結束和函數調用後的下一行之間,值已經改變。我認爲,因爲v是一個指針,它應該保留這個值。如果有人可以請告訴我爲什麼價值正在改變,將不勝感激。我已經用完了想法,不知道該怎麼做。在c中,函數調用後值從函數末尾變爲函數外
/*
* File: main.c
* Author: user1
*
* Created on April 7, 2015, 3:57 PM
*/
#include <stdio.h>
#include <stdlib.h>
/*
* File: main.c
* Author: user1
*
* Created on April 7, 2015, 3:57 PM
*/
/*
*
*/
# ifndef TYPE
# define TYPE int
# endif
struct DynArr
{
TYPE *data;
int size;
int capacity;
};
/* pointer to the data array */
/* Number of elements in the array */
/* capacity ofthe array */
void initDynArr(struct DynArr *v, int capacity)
{
v->data = malloc(sizeof(TYPE) * capacity);
//assert(v->data != 0);
v->size = 0;
v->capacity = capacity;
}
void freeDynArr(struct DynArr *v)
{
if(v->data != 0)
{
free(v->data); /* free the space on the heap */
v->data = 0;
/* make it point to null */
}
v->size = 0;
v->capacity = 0;
}
int sizeDynArr(struct DynArr *v)
{
return v->size;
}
/*
void addDynArr(struct DynArr *v, TYPE val)
{
// Check to see if a resize is necessary
if(v->size == v->capacity)
_setCapacityDynArr(v, 2 * v->capacity);
v->data[v->size] = val;
v->size++;
}
*/
void addDynArr(struct DynArr *v, TYPE val)
{
// Check to see if a resize is necessary
if(v->size >= v->capacity)
{
_setCapacityDynArr(v, 2 * v->capacity);
printf(">>>%d",v->size); //<<<<<<<<<<<<<<<<<<<<v->size = 0
v->data[v->size] = val;
v->size++;
printf("setcapacity: size is: %d capacity is: %d value is %d value in array is: %d\n", v->size, v->capacity, val, v->data[v->size-1]);
}
else
{
v->data[v->size] = val;
v->size++;
printf("not setcapacity: size is: %d capacity is: %d value is %d value in array is: %d\n", v->size, v->capacity, val, v->data[v->size-1]);
}
//printf("%d\n", v->capacity);
}
void removeDynArray(struct DynArr *b, TYPE v)
{
for(int i = 0; i < b->size; i++)
{
if(b->data[i] == v)
{
while(i < (b->size))
{
b->data[i] = b->data[i+1];
i++;
}
break;
}
}
b->size--;
}
void print(struct DynArr *v)
{
for(int i = 0; i < v->size; i++)
{
printf("%d\n", v->data[i]);
}
}
//do this
void _setCapacityDynArr(struct DynArr *v, int newCap)
{
struct DynArr* temp;
temp = v;
///print(temp);
//struct DynArr v;
v = malloc(sizeof(struct DynArr));
v->data = malloc(sizeof(TYPE) * newCap);
v->capacity = newCap;
v->size = 0; //temp size is also being set
for (int i = 0 ; i < temp->size; i++)
{
v->data[i] = temp->data[i];
v->size++;
}
free(temp->data);
temp->size = 0;
temp->capacity = 0;
temp = 0;
printf(">!>>%d",v->size); //////////<<<<<<<<<<<<<<<<<<<<<<<<v->size = 2
}
int main(int argc, char** argv)
{
struct DynArr a;
initDynArr(&a, 2);
addDynArr(&a, 5);
addDynArr(&a, 7);
addDynArr(&a, 8);
//printf("%d\n", a.size);
//print(&a);
// printf ("%d\n",a.data[2]);
return (EXIT_SUCCESS);
}
請將代碼粘貼到您的問題中,而不是鏈接。你永遠不知道鏈接何時停止工作。 –
請格式化,難以閱讀。 –