[英]Program receives signal - gdb
對於以下問題 ,
Exercise 12335 - Write a C program to read through an array of any type. Write a C program to scan through this array to find a particular value.
這是我的解決方案:
#include<stdio.h>
enum types
{
integer,
character,
floatValue
};
void f(void *, enum types);
void doSomething(void *, enum types);
int main(){
int a[] ={1,2,3};
enum types type = integer;
f(a, type);
}
void f(void *ptr, enum types type){
switch(type){
case(integer):
if(sizeof((int *)ptr)/sizeof(int) > 1){
doSomething(&((int *)ptr)[1], type); // Print second element
}
break;
case(character):
if(sizeof((char *)ptr)/sizeof(char) > 1){
doSomething(&((int *)ptr)[1], type); // Print second element
}
break;
case(floatValue):
if(sizeof((float *)ptr)/sizeof(float) > 1){
doSomething(&((int *)ptr)[1], type); // Print second element
}
break;
}
}
void doSomething(void *ptr, enum types type){
switch(type){
case(integer):
printf("%d", *(int *)ptr);
break;
case(character):
printf("%c", *(char *)ptr);
break;
case(floatValue):
printf("%f", *(float *)ptr);
break;
}
}
> gcc -g temp.c -o program.exe
> gdb program.exe
以下是gdb輸出:
題:
為什么program.exe
不起作用?
您無法僅基於指針找到數組的大小(指針只是一個地址-它不包含有關其指向的任何信息)。
下面是一個修改函數的解決方案,並將數組大小作為參數傳遞。
#include<stdio.h>
enum types
{
integer,
character,
floatValue
};
void f(void *, enum types, int a_size);
void doSomething(void *, enum types);
int main(){
int a[] ={1,2,3};
enum types type = integer;
f(a, type, sizeof(a));
}
void f(void *ptr, enum types type, int a_size){
switch(type){
case(integer):
if(a_size/sizeof(int) > 1){
doSomething(&((int *)ptr)[1], type); // Print second element
}
break;
case(character):
if(a_size/sizeof(char) > 1){
doSomething(&((int *)ptr)[1], type); // Print second element
}
break;
case(floatValue):
if(a_size/sizeof(float) > 1){
doSomething(&((int *)ptr)[1], type); // Print second element
}
break;
}
}
void doSomething(void *ptr, enum types type){
switch(type){
case(integer):
printf("%d", *(int *)ptr);
break;
case(character):
printf("%c", *(char *)ptr);
break;
case(floatValue):
printf("%f", *(float *)ptr);
break;
}
}
我不確定它是否可以解決您的gdb問題(我使用的是Linux,而不是Windows,並且未收到任何信號),但是該程序可以正常運行。
[更新]
這是一個樣式,但是我將更新f
函數,使其看起來像這樣:
void f(void *ptr, enum types type, int a_size){
int unit_size;
switch(type){
case(integer):
unit_size = sizeof(int);
break;
case(character):
unit_size = sizeof(char);
break;
case(floatValue):
unit_size = sizeof(float);
break;
default:
break;
}
if((a_size/unit_size) > 1){
doSomething(&((int *)ptr)[1], type); // Print second element
}
}
它使可讀性更高,添加不同類型的速度更快,並且如果將調用更改為doSomething
,則只需在一個地方進行修改即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.