我一直在尝试将字符串数组传递给函数。虽然我知道执行此操作的其他过程,但我特别想确切地知道为什么这个特定代码不起作用
我尝试过以下方式
#include<stdio.h>
void check_number(char* str[])
{
int sum=0;
int i=0;
while(str[0][i]!='/0')
{
char a='a';
sum=sum+str[0][i]-(int)(a);
}
printf("number = %d ",sum);
}
int main()
{
char* str[2];
printf("Enter a string ");
scanf("%s",str[0]);
printf("Enter a string ");
scanf("%s",str[1]);
check_number(str);
return 0;
}
最佳答案
这是此处发布的代码中的问题之一
char* str[2];
str
是两个字符指针的数组,即 str[0]
和 str[1]
是字符指针,即它们需要使用有效地址进行初始化,但您尚未为它们分配内存。
scanf("%s",str[0]); /* No memory allocated for str[0] */
scanf("%s",str[1]); /* No memory allocated for str[1] */
在将数据扫描到其中之前,您需要为 str[0]
和 str[1]
分配内存。例如
int main(void)
{
char* str[2];
for(int i = 0; i < 2 ; i++) {
printf("Enter a string ");
str[i] = malloc(MAX_BUF_SIZE); /*define this macro for no of bytes */
scanf("%s",str[i]);
}
/* do some stuff */
/* free dynamically allocated memory for each str[index] */
return 0;
}
还有一个问题
while(str[0][i]!='\0') { /* '/0' --> '\0' */
char a='a';
sum=sum+str[0][i]-(int)(a); /* what you want to achieve here, please explain */
}
这个循环什么时候终止?应该有一个循环终止条件,否则它将无限循环。
关于c - 将字符串数组作为字符指针传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57240379/