为什么For-Loop自身会终止所有代码?

问题描述

for循环完成myArray的打印后,它完全不再允许任何其他代码继续运行,并返回值-1073741819。

const SuspensefulUserProfile = ({ userId }) => {
  const [data,setData] = useState();

  useEffect(() => {
    fetchUserProfile(userId).then(setData);
  },[userId])

  return data ? <UserProfile data={data} /> : 'Loading...';
};

解决方法

表达式

myArray[i] != '\0' 

等同于

myArray[i] != NULL 

但是您的数组不包含值为NULL的元素。

所以要么像这样声明数组

char *myArray[]={"Carmaker1","Carmaker2","Carmaker3","Carmaker4","Carmaker5","Carmaker6",NULL};

(向初始化器添加值NULL)并使用循环

for ( int i = 0 ; myArray[i] != NULL ; i++ ) {
    
    printf("%s ",*(myArray+i));
}

或者您可以在数组后面附加一个空字符串,例如

char *myArray[]={"Carmaker1",""};

并像这样写循环

for ( int i = 0 ; myArray[i][0] != '\0' ; i++ ) {
    
    printf("%s ",*(myArray+i));
}

或使用数组的当前声明以以下方式更改循环

for ( size_t i = 0 ; i!= sizeof( myArray ) / sizeof( *myArray ) ; i++ ) {
    
    printf("%s ",*(myArray+i));
}
,

您的代码存在错误,如注释中所建议,您可以按如下所示修复代码,

#include<stdio.h>

int main() {

char *myArray[]=  {"Carmaker1",""};

for ( int i = 0 ; *myArray[i] != '\0' ; i++ ) {printf("%d,%s \n",i,*(myArray+i)); }

}