我从 C 开始,来自 meta c 语言,PHP 和 HTML 基础,短时间
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
compare(const void * a, const void * b){
return ( *(int*)a - *(int*)b );
}
int main(){
int arr_size = 10;
int j;
char array[arr_size][2];
char str[50];
char output[50];
// fill the array with string and random integers
for (j=0; j<arr_size; j++) {
strcpy(str, "array");
array[j][0] = str; //i've should put *str
array[j][1] = rand() % arr_size+1;
}
// print the array
for (j=0; j<arr_size; j++) {
strcpy(str, "");
strcpy(output, "");
sprintf(str, "%u", array[j][0]); // %u should be %s but return me segmentation fault
strcat(output, str);
strcat(output, " ");
sprintf(str, "%i", array[j][1]);
strcat(output, str);
printf(output); printf("\n");
}
printf("\n");
}
这是完整代码,看
array[j][0] = str;
和
sprintf(str, "%u", array[j][0]);
我需要在str (*str)
之前放置*
来传递警告信息,但我没有声明任何指针。为什么要使用这个解决方案?
如果我将 %u
更改为 %s
,它会返回段错误,这是什么问题?
最佳答案
array[j][0]
是 char
。您不能为其分配字符数组。 *str
只是 str
中的第一个字符,所以这个赋值是有效的。
出于同样的原因,您不能使用 %s
打印它 - 此说明符用于打印以 nul 结尾的字符串,而不是单个字符。
您也不能执行 sprintf(str, "%s", array[j]);
,因为它不是以 nul 结尾的/
关于c - 警告 : assignment makes integer from pointer without a cast, 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9666361/