问题描述
我有一个堆栈实现来存储变量:char *items 在堆栈上。但是由于某种原因,当我使用 stack->items[position] 时,它会将其视为常规字符(不是指针),并且我无法在堆栈上存储完整字符(它是 URL)。
我想给 push 函数一个 char *(这是一个 URL),我想把它放在我的堆栈中,要么:
p->items[p->pos] = item;
或
strcpy(p->items[p->pos],item);
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "shm_stack.h"
typedef struct int_stack{
int size; /* the max capacity of the stack */
int pos; /* position of last item pushed onto the stack */
char *items; /* stack of stored chars */
} ISTACK;
int is_full(ISTACK *p){
if ( p == NULL ) {
return 0;
}
return ( p->pos == (p->size -1) );
}
int sizeof_shm_stack(int size){
return (sizeof(ISTACK) + sizeof(char) * size);
}
int init_shm_stack(ISTACK *p,int stack_size){
if ( p == NULL || stack_size == 0 ) {
return 1;
}
p->size = stack_size;
p->pos = -1;
p->items = (char *) (p + sizeof(ISTACK));
return 0;
}
ISTACK *create_stack(int size){
int mem_size = 0;
ISTACK *pstack = NULL;
if ( size == 0 ) {
return NULL;
}
mem_size = sizeof_shm_stack(size);
pstack = malloc(mem_size);
if ( pstack == NULL ) {
perror("malloc");
} else {
char *p = (char *)pstack;
pstack->items = (char *) (p + sizeof(ISTACK));
pstack->size = size;
pstack->pos = -1;
}
return pstack;
}
void destroy_stack(ISTACK *p){
if ( p != NULL ) {
free(p);
}
}
int push(ISTACK *p,char *item){
if ( p == NULL ) {
return -1;
}
if ( !is_full(p) ) {
++(p->pos);
//p->items[p->pos] = item;
strcpy(p->items[p->pos],item);
//printf("push method: %d\n",p->items[p->pos]);
return 0;
} else {
return -1;
}
}
问题出在我的 push 方法中,我既不能使用 strcpy() 也不能只将 char 分配给 p->items[p-pos] 而没有说诸如“从不兼容的类型 char * 分配 char”之类的内容,但取消引用“item”只会让我得到第一个字符,而我想要整个“string”。
为什么会发生这种情况,我该如何解决?
解决方法
p->items
是 char*
,所以 p->items[...]
是 char
。 strcpy
需要 char*
,因此您提供的内容与需要的内容不匹配。
不仅如此,它还期望指针指向足够多的字符中的第一个以包含被复制的字符串。您甚至没有尝试获取 item
指向的字符串的长度,更不用说分配了足够的内存。
我想你想要一堆字符串。如果是这样,我们需要一个指针数组(char *items[]
)或一个指向内存块的指针(char **items
)。后者在这里更简单。因此,
char *items;
应该
char **items;
它会被分配使用
malloc(sizeof(char*) * size)
有两种方法可以将字符串添加到堆栈中。
-
堆栈可以取得所提供字符串的所有权。
p->items[p->pos] = item;
-
堆栈可以复制提供的字符串。
p->items[p->pos] = strdup(item);
区别在于谁负责释放字符串。